Offline learning atlas / Foundation 0.11.0

Programming and Scripting Atlas

One registry. Progressive tested packs. A source that keeps every edition aligned.

285registry entries
20families
19tested packs
225examples and solutions

Local and downloadable. No API keys, network calls or automatic execution of pasted code. Version 0.11.0, 2026-10-26.

Master registry

Comprehensive, extensible starting registry; not an exhaustive list of every language, dialect or notation. Each item has one stable ID and can belong to multiple families. Planned means no pack has been built. 28 entries have introductory tested coverage; 257 remain planned.

Languages, dialects, notations and formats; overlays counted separately
EntryKindStatusEvidence

Framework, runtime and tool overlays

These 30 planned overlays are separate from the 285 registry entries. p5.js and openFrameworks belong here; they are libraries or toolkits, not extra programming languages.

OverlayKindRelated entry IDsStatus
p5.jsJavaScript libraryjavascriptplanned
openFrameworksC++ toolkitcppplanned
Node.jsJavaScript runtimejavascriptplanned
DenoJavaScript and TypeScript runtimejavascript, typescriptplanned
BunJavaScript runtime and toolkitjavascript, typescriptplanned
ReactUI libraryjavascript, typescriptplanned
VueUI frameworkjavascript, typescriptplanned
SvelteUI compiler and frameworkjavascript, typescriptplanned
DjangoPython web frameworkpython, django-template-languageplanned
FlaskPython web frameworkpythonplanned
FastAPIPython web frameworkpythonplanned
Ruby on RailsRuby web frameworkrubyplanned
LaravelPHP frameworkphpplanned
SpringJVM frameworkjava, kotlinplanned
.NETruntime and platformcsharp, fsharp, visual-basic-netplanned
FlutterUI toolkitdartplanned
Godotgame enginegdscript, csharpplanned
Unitygame enginecsharpplanned
Unreal Enginegame enginecpp, unreal-blueprintsplanned
Terraforminfrastructure toolhclplanned
Ansibleautomation toolyamlplanned
Kubernetesorchestration platformyamlplanned
Gitversion control toolCross-cuttingplanned
PostgreSQLdatabase runtimepostgresql-sql, pl-pgsqlplanned
SQLitedatabase enginesqlite-sqlplanned
Jupyternotebook environmentpython, r, juliaplanned
Processing IDEcreative coding environmentprocessing-languageplanned
Dockercontainer tooldockerfileplanned
LLVMcompiler infrastructurellvm-irplanned
CUDA ToolkitGPU platform and toolscuda-cppplanned
Tested learning pack

Web Foundations: HTML, CSS and JavaScript

Structure, styling, pure functions, input handling, events and local list filtering. No backend, deployment, authentication, network APIs or framework instruction.

Beginners who can save a plain text file and open it in a browser. Allow 3 to 5 hours, at your own pace.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Export this standalone HTML example and open it separately in the browser. See the example test record for the tested version and operating system.

1. Start with a small, observable change

Save a copy of an example with an .html extension and open that copy in a browser. Keep the Atlas open as a reference. Change one value, reload the example and compare the result with its expected output. Use the browser developer tools console for errors and the Elements panel for structure and computed styles. The Atlas itself does not run pasted code. These examples are complete files, so there is no build step, package manager or server.

2. HTML gives content its structure

Use a descriptive title, the page language and a viewport declaration. Put the main content in main, identify it with a meaningful h1, and use headings in a logical hierarchy. Lists express a collection of related items. Use buttons for actions and links for navigation. Associate a visible label with each input. These choices help readers, keyboards and assistive technology before any CSS or JavaScript is added. See examples 01 and 05.

3. CSS controls presentation and layout

A rule pairs a selector with declarations. Scope a component with a class rather than changing every element globally. The box model distinguishes content, padding, border and margin; border-box includes padding and border within a declared width. In example 02, grid defines columns and gap separates the cards. Start with a narrow layout and add a media query only when the content benefits. Inspect the computed style when a declaration appears not to work.

4. JavaScript transforms data and reacts to events

Use const when the binding will not be reassigned and let when state will change. A function takes inputs and returns a result; a return ends that function call. Keep calculations separate from DOM updates so boundary cases can be tested directly. Arrays hold ordered values; filter keeps matching items, while reduce combines them. Use explicit input validation rather than allowing text or missing values to become surprising numbers. See examples 03 and 06.

5. Events connect behavior to controls

Use addEventListener to register a handler. Keep state and displayed output synchronized through one rendering function when multiple controls affect the same value. A form submit handler can use preventDefault to stay on the page. textContent inserts text without interpreting it as HTML; use it for names, search terms and other input. A polite status region can announce changes, but it does not replace visible text or proper labels. See examples 04 and 05.

6. Debug with a reproducible observation

Record the smallest steps that show the problem, the input, expected output, actual output and exact error message. Check the first console error before treating later errors as independent failures. A missing DOM element often indicates a selector typo or code running before the element exists. A layout problem can come from the wrong selector, an overridden declaration or an overflowing width. Reduce the failing case, make one change, then rerun both the failing case and a normal case.

7. Test behavior, boundaries and access

For each interaction test the initial state, a normal input, an empty or boundary input, repeated actions and recovery. Try Tab, Shift+Tab, Enter and Space on native controls. Check visible focus, narrow widths and text zoom. Confirm labels remain visible and errors offer a next action. Automated checks here cover recorded invariants in one browser; they do not prove every accessibility criterion or cross-browser behavior. A screen reader and another browser remain useful follow-up checks.

8. Refactor and document after behavior is stable

Write down the observable contract before reorganizing code. Extract repeated rendering or validation into a named function; preserve inputs, outputs and error behavior. Rerun the same tests afterward. Document how to open the file, required runtime, expected output, limitations and test date. Do not put tokens, passwords or private work into a prompt preset. Export presets if you need a durable copy: file-URL localStorage behavior can vary or be blocked.

Quick reference

HTML

main / section / article

Main content; thematic group; independently meaningful content. Choose by meaning.

HTML

h1 through h6

Headings describe hierarchy; do not choose a level only for its font size.

HTML

label for="id"

Associate a visible label with the input whose id matches.

HTML

button type="button"

An action button that does not implicitly submit a surrounding form.

HTML

required / maxlength

Useful browser input constraints; still validate application-specific rules.

CSS

.class / element / #id

Class, type and ID selectors target different sets of elements.

CSS

box-sizing: border-box

Declared dimensions include padding and border; margin remains outside.

CSS

display: grid / gap

Create a grid layout and separate its tracks without spacer elements.

CSS

@media (min-width: 48rem)

Apply a rule only when the viewport condition matches.

CSS

:focus-visible

Make keyboard focus easy to locate; never remove a useful outline without a replacement.

JavaScript

const / let

Use const for bindings you do not reassign; let for bindings you do.

JavaScript

Number.isFinite(value)

Accept a finite number without coercing a string to a number.

JavaScript

array.filter / array.reduce

Build a subset; combine a sequence into a result.

DOM

querySelector / createElement

Locate an element; create a new element explicitly.

DOM

addEventListener / textContent

React to an event; display plain text.

DOM

replaceChildren

Replace the child nodes, useful for reconstructing a small local result list.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

01 - Structure a useful page

The heading identifies the page. A named section groups the checklist. Native list markup preserves item relationships without styling or JavaScript.

Expected: One main landmark, one level-one heading and a two-item list.

Test record: passed; Chrome/155.0.8059.86; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; form-action 'none'; base-uri 'none'">
<title>01 - Structure a useful page</title>
<style>
body { font: 18px/1.5 system-ui; margin: 2rem; color: #173344; }
button, input { font: inherit; padding: .4rem; }
:focus-visible { outline: 3px solid #964b00; outline-offset: 3px; }

</style>
<main>
<h1>Weekend workshop</h1>
<p>Build a small page from plain text.</p>
<section aria-labelledby="materials">
  <h2 id="materials">Bring these materials</h2>
  <ul><li>A text editor</li><li>A browser</li></ul>
</section>
</main>

</html>
02 - Build a responsive layout

A class selector scopes the layout. The default is one column; the media query changes it at 48rem. Gap separates cards, while padding separates each card border from its content.

Expected: One card column at 375px; three columns at 1024px. Padding stays inside each border-box.

Test record: passed; Chrome/155.0.8059.86; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; form-action 'none'; base-uri 'none'">
<title>02 - Build a responsive layout</title>
<style>
body { font: 18px/1.5 system-ui; margin: 2rem; color: #173344; }
button, input { font: inherit; padding: .4rem; }
:focus-visible { outline: 3px solid #964b00; outline-offset: 3px; }
* { box-sizing: border-box; }
.cards { display: grid; grid-template-columns: 1fr; gap: 1rem; }
article { border: 2px solid #426c80; padding: 1rem; }
@media (min-width: 48rem) {
  .cards { grid-template-columns: repeat(3, 1fr); }
}
</style>
<main>
<h1>Study plan</h1>
<div class="cards">
  <article><h2>Read</h2><p>Inspect one example.</p></article>
  <article><h2>Change</h2><p>Alter one value.</p></article>
  <article><h2>Test</h2><p>Check the result.</p></article>
</div>
</main>

</html>
03 - Separate calculation from display

A pure calculation returns a value without changing the page. Validation rejects bad inputs at the boundary. The final statement formats a result and writes plain text into the document.

Expected: Total: 45 minutes. An empty array returns 0. Negative or nonnumeric values throw TypeError.

Test record: passed; Chrome/155.0.8059.86; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; form-action 'none'; base-uri 'none'">
<title>03 - Separate calculation from display</title>
<style>
body { font: 18px/1.5 system-ui; margin: 2rem; color: #173344; }
button, input { font: inherit; padding: .4rem; }
:focus-visible { outline: 3px solid #964b00; outline-offset: 3px; }

</style>
<main>
<h1>Workshop total</h1>
<p id="result"></p>
</main>
<script>
function totalMinutes(values) {
  if (!Array.isArray(values) || values.some(value =>
      !Number.isFinite(value) || value < 0)) {
    throw new TypeError("Use an array of non-negative numbers.");
  }
  return values.reduce((sum, value) => sum + value, 0);
}
document.querySelector("#result").textContent =
  `Total: ${totalMinutes([15, 20, 10])} minutes`;
</script>
</html>
04 - Connect a button to state

The variable stores state. An event listener updates that state after a button activation. A native button supplies keyboard behavior. A status region makes a polite announcement possible in assistive technology.

Expected: Starts at Count: 0. Each activation adds one; three activations display Count: 3.

Test record: passed; Chrome/155.0.8059.86; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; form-action 'none'; base-uri 'none'">
<title>04 - Connect a button to state</title>
<style>
body { font: 18px/1.5 system-ui; margin: 2rem; color: #173344; }
button, input { font: inherit; padding: .4rem; }
:focus-visible { outline: 3px solid #964b00; outline-offset: 3px; }

</style>
<main>
<h1>Practice counter</h1>
<button id="add" type="button">Add one</button>
<p id="count" role="status">Count: 0</p>
</main>
<script>
let count = 0;
document.querySelector("#add").addEventListener("click", () => {
  count += 1;
  document.querySelector("#count").textContent = `Count: ${count}`;
});
</script>
</html>
05 - Handle form input safely

The label matches the input ID. The submit handler prevents navigation, trims whitespace and renders text. Native required validation catches an empty value; the explicit check also catches whitespace-only input.

Expected: Ada produces Hello, Ada! Spaces produce a useful message. Markup-like text is displayed literally.

Test record: passed; Chrome/155.0.8059.86; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; form-action 'none'; base-uri 'none'">
<title>05 - Handle form input safely</title>
<style>
body { font: 18px/1.5 system-ui; margin: 2rem; color: #173344; }
button, input { font: inherit; padding: .4rem; }
:focus-visible { outline: 3px solid #964b00; outline-offset: 3px; }

</style>
<main>
<h1>Personal greeting</h1>
<form id="greeting">
  <label for="name">Your name</label>
  <input id="name" name="name" maxlength="60" required>
  <button type="submit">Greet me</button>
</form>
<p id="message" role="status"></p>
</main>
<script>
document.querySelector("#greeting").addEventListener("submit", event => {
  event.preventDefault();
  const name = document.querySelector("#name").value.trim();
  document.querySelector("#message").textContent =
    name ? `Hello, ${name}!` : "Enter a name with visible characters.";
});
</script>
</html>
06 - Filter a local list

Filter creates a matching array without modifying the source list. The render function rebuilds the displayed list using text nodes. An empty result has an explicit count rather than an unexplained blank space.

Expected: Initially 3 topics. Searching CSS leaves CSS layout. An unmatched search gives 0 topics.

Test record: passed; Chrome/155.0.8059.86; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; form-action 'none'; base-uri 'none'">
<title>06 - Filter a local list</title>
<style>
body { font: 18px/1.5 system-ui; margin: 2rem; color: #173344; }
button, input { font: inherit; padding: .4rem; }
:focus-visible { outline: 3px solid #964b00; outline-offset: 3px; }

</style>
<main>
<h1>Find a study topic</h1>
<label for="query">Search topics</label>
<input id="query" type="search">
<p id="matches" role="status"></p>
<ul id="topics"></ul>
</main>
<script>
const topics = ["HTML structure", "CSS layout", "JavaScript events"];
function renderTopics() {
  const query = document.querySelector("#query").value.trim().toLowerCase();
  const matches = topics.filter(topic => topic.toLowerCase().includes(query));
  const list = document.querySelector("#topics");
  list.replaceChildren();
  for (const topic of matches) {
    const item = document.createElement("li");
    item.textContent = topic;
    list.append(item);
  }
  document.querySelector("#matches").textContent = `${matches.length} topics`;
}
document.querySelector("#query").addEventListener("input", renderTopics);
renderTopics();
</script>
</html>
Exercise A solution - Step and reset

Try it first: Starting from example 04, add two per activation and provide Reset. Keep both updates in one render function. Check two activations and a reset with the keyboard.

Both handlers share rendering, so the displayed text has one owner. Reset updates the state as well as the text, avoiding a stale count on the next activation.

Expected: Two Add two activations display Count: 4. Reset displays Count: 0.

Test record: passed; Chrome/155.0.8059.86; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; form-action 'none'; base-uri 'none'">
<title>Exercise A solution - Step and reset</title>
<style>
body { font: 18px/1.5 system-ui; margin: 2rem; color: #173344; }
button, input { font: inherit; padding: .4rem; }
:focus-visible { outline: 3px solid #964b00; outline-offset: 3px; }

</style>
<main>
<h1>Practice in pairs</h1>
<button id="add" type="button">Add two</button>
<button id="reset" type="button">Reset</button>
<p id="count" role="status">Count: 0</p>
</main>
<script>
let count = 0;
function render() {
  document.querySelector("#count").textContent = `Count: ${count}`;
}
document.querySelector("#add").addEventListener("click", () => {
  count += 2;
  render();
});
document.querySelector("#reset").addEventListener("click", () => {
  count = 0;
  render();
});
</script>
</html>
Exercise B solution - Remaining minutes

Try it first: Write remainingMinutes(limit, used). Reject negative, infinite and nonnumeric inputs. Clamp overspending to zero. Test equal, under and over budget cases.

Validation defines the accepted domain. Math.max supplies an explicit lower bound. No browser-specific operation is needed inside the calculation.

Expected: Remaining: 15 minutes. Over budget returns 0. Invalid input throws TypeError.

Test record: passed; Chrome/155.0.8059.86; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; form-action 'none'; base-uri 'none'">
<title>Exercise B solution - Remaining minutes</title>
<style>
body { font: 18px/1.5 system-ui; margin: 2rem; color: #173344; }
button, input { font: inherit; padding: .4rem; }
:focus-visible { outline: 3px solid #964b00; outline-offset: 3px; }

</style>
<main>
<h1>Time left</h1><p id="remaining"></p>
</main>
<script>
function remainingMinutes(limit, used) {
  if (![limit, used].every(value => Number.isFinite(value) && value >= 0)) {
    throw new TypeError("Use non-negative finite numbers.");
  }
  return Math.max(0, limit - used);
}
document.querySelector("#remaining").textContent =
  `Remaining: ${remainingMinutes(60, 45)} minutes`;
</script>
</html>
Exercise C solution - A useful empty state

Try it first: Extend example 06 with a singular count and a useful empty-result message. Confirm an empty query restores the entire list.

The empty state tells the learner how to recover. The source array stays unchanged, so clearing the query can always reconstruct the complete list.

Expected: CSS gives 1 topic. An unmatched query gives a recovery message. Clearing restores 3 topics.

Test record: passed; Chrome/155.0.8059.86; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; form-action 'none'; base-uri 'none'">
<title>Exercise C solution - A useful empty state</title>
<style>
body { font: 18px/1.5 system-ui; margin: 2rem; color: #173344; }
button, input { font: inherit; padding: .4rem; }
:focus-visible { outline: 3px solid #964b00; outline-offset: 3px; }

</style>
<main>
<h1>Search practice topics</h1>
<label for="query">Search topics</label><input id="query" type="search">
<p id="matches" role="status"></p><ul id="topics"></ul>
</main>
<script>
const topics = ["HTML structure", "CSS layout", "JavaScript events"];
function renderTopics() {
  const query = document.querySelector("#query").value.trim().toLowerCase();
  const matches = topics.filter(topic => topic.toLowerCase().includes(query));
  const list = document.querySelector("#topics");
  list.replaceChildren();
  for (const topic of matches) {
    const item = document.createElement("li");
    item.textContent = topic;
    list.append(item);
  }
  document.querySelector("#matches").textContent = matches.length === 0
    ? "No topics match. Clear the search to see all topics."
    : `${matches.length} ${matches.length === 1 ? "topic" : "topics"}`;
}
document.querySelector("#query").addEventListener("input", renderTopics);
renderTopics();
</script>
</html>
Tested learning pack

Python Foundations

Core types, control flow, functions, collections, temporary toy files, JSON, expected errors, local modules and unittest. No package installation, external data, deployment or service integration.

Beginners who can save a text file and run an installed Python interpreter. Allow 4 to 6 hours, at your own pace.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

This pack was tested with the installed CPython 3.9.6 on macOS 27.0.1. Python 3.9 is no longer supported upstream; this is a recorded offline learning environment, not a recommended deployment runtime. The cited 3.9 documentation currently describes 3.9.25, while the actual examples were tested on 3.9.6. No installation is needed or performed here. Save the example in a practice folder and run python3 followed by its quoted filename. Modules need the companion file beside the entry file. The browser Atlas exports text only and never runs Python.

1. Run the installed interpreter deliberately

This pack was tested with the installed CPython 3.9.6 on macOS 27.0.1. Python 3.9 is no longer supported upstream; this is a recorded offline learning environment, not a recommended deployment runtime. The cited 3.9 documentation currently describes 3.9.25, while the actual examples were tested on 3.9.6. No installation is needed or performed here. Save the example in a practice folder and run python3 followed by its quoted filename. Modules need the companion file beside the entry file. The browser Atlas exports text only and never runs Python.

2. Values, names and explicit conversions

Python names refer to objects. This pack starts with int, float, bool, str and None, then collections. Use type or isinstance to investigate a value. The int constructor converts integer text and raises an error for invalid text. Use f-strings to format an output without changing the underlying value. A float is not an exact decimal arithmetic model; these examples use minutes and simple teaching values rather than financial calculations. Strings are immutable, so methods such as strip return a result you can assign or use.

3. Control flow follows indentation

Use if, elif and else for conditions. A for loop visits items in an iterable; enumerate adds a counter and range produces integers with an excluded stop value. A while loop needs a condition that can become false. Four spaces per indentation level make the examples easy to inspect. Keep state changes close to the condition they affect. Predict the first, last and empty-loop cases before running. Example 02 combines iteration, a conditional expression and a bounded countdown.

4. Functions make contracts visible

A function binds arguments to parameters and returns a result; without an explicit return value it returns None. Keep reusable calculations separate from printing or file access. State the accepted types, boundary values and errors. Avoid mutable default arguments in beginner helpers; create a fresh list inside a function when needed. Boolean is a subclass of integer, so a contract that excludes True and False needs an explicit check. Example 03 deliberately accepts whole-number minutes and tests invalid input.

5. Choose a collection for the relationship

Lists represent ordered mutable sequences, tuples fixed groupings, dictionaries key/value relationships and sets unique values. A comprehension can transform or filter a list, but a simple loop is often clearer when it also updates a dictionary. Use get with a default for counting. Sets have no promised display order; sort one before making deterministic output. A new list of references does not deep-copy the contained objects. The examples read records and build summaries without mutating the source records.

6. Keep file practice small and disposable

File paths have effects, so the toy examples create a new TemporaryDirectory inside the current writable practice folder. They use fixed filenames inside it, explicit UTF-8 encoding and context managers. They read only what they wrote, then let the context manager remove the temporary directory. A with block closes a file even when an exception interrupts the block. JSON is data, not code: serialize a tiny dictionary and decode only that bounded input. Never substitute a real document path into these exercises.

7. Errors should support recovery

Read the final exception type and message, then follow the traceback to the relevant call. Catch a specific expected exception where you can recover or add context; do not hide every error with a bare except. Validation can raise TypeError for the wrong kind of input and ValueError for a value outside the contract. A try/except/else structure distinguishes successful work from recovery. Keep the input that triggered a failure so a test can reproduce it. Examples 05 and Exercise B show deliberate recovery.

8. Modules and tests keep changes controlled

A module is a Python file. Save study_tools.py beside example 08 and import its named function. The main guard separates importing definitions from running the demonstration. Avoid naming your files json.py or unittest.py, which can hide the standard library modules in normal script execution. Use unittest to check normal, boundary and invalid cases. The included harness runs each authored example in a fresh temporary directory with a timeout and bytecode writing disabled; that is controlled testing of trusted examples, not a security sandbox for arbitrary code.

Quick reference

Types

int / float / bool / str / None

Whole numbers, floating-point values, truth values, text and absence of a value.

Flow

if / elif / else

Choose a block using a condition.

Flow

for / enumerate / range

Visit values, add counters and generate bounded integer sequences.

Flow

while

Repeat while a condition remains true; ensure progress toward stopping.

Functions

def / return

Define a reusable operation and give its result to the caller.

Collections

list / tuple

Ordered mutable sequence / fixed grouping.

Collections

dict.get(key, default)

Look up a key with an explicit fallback.

Collections

set / sorted

Deduplicate, then sort when stable output matters.

Errors

try / except / else

Handle a specific failure and separate the successful branch.

Errors

raise TypeError / ValueError

Signal a contract violation rather than silently producing a misleading result.

Files

with open(..., encoding="utf-8")

Close the handle reliably and make text encoding explicit.

Files

TemporaryDirectory(dir=".")

Create a disposable toy directory under the practice folder.

Data

json.dumps / json.loads

Encode and decode bounded JSON data.

Modules

from study_tools import total_minutes

Reuse a named function from a companion module.

Modules

if __name__ == "__main__"

Run the demonstration only when executed as the entry script.

Tests

unittest.TestCase / assertEqual / assertRaises

Check observable results and expected errors.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Python 01 - Values and strings

Names refer to values. Division produces a float here, while a comparison produces a Boolean. The f-string formats display without changing the stored value. String methods return strings.

Expected stdout:

Ada: 45 minutes
Average: 22.5
int float bool
PYTHON

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

name = "Ada"
minutes = 45
sessions = 2
average = minutes / sessions
ready = sessions > 0
print(f"{name}: {minutes} minutes")
print(f"Average: {average:.1f}")
print(type(minutes).__name__, type(average).__name__, type(ready).__name__)
print("  Python  ".strip().upper())
Python 02 - Branches and loops

Indentation defines blocks. enumerate gives each item a number. The while loop changes the value that controls termination. The stop value of range is excluded.

Expected stdout:

Session 1: short
Session 2: long
Session 3: short
Countdown: 0
Range sum: 6

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

minutes = [5, 20, 10]
for index, value in enumerate(minutes, start=1):
    label = "long" if value >= 15 else "short"
    print(f"Session {index}: {label}")
countdown = 3
while countdown > 0:
    countdown -= 1
print(f"Countdown: {countdown}")
print(f"Range sum: {sum(range(1, 4))}")
Python 03 - Functions and contracts

This function accepts only integer minute counts, explicitly excluding Boolean values. It returns a result rather than printing internally. Errors define the input contract, and zero is the lower bound.

Expected stdout:

Remaining: 15
Over budget: 0

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

def remaining_minutes(limit, used):
    if any(type(value) is not int for value in (limit, used)):
        raise TypeError("Use whole-number minutes.")
    if limit < 0 or used < 0:
        raise ValueError("Minutes must be non-negative.")
    return max(0, limit - used)

print(f"Remaining: {remaining_minutes(60, 45)}")
print(f"Over budget: {remaining_minutes(10, 12)}")
Python 04 - Collections and transformations

A list keeps an ordered sequence, dictionaries associate keys with values, a set deduplicates topics and a tuple holds a fixed pair. Sorting the set makes printed output deterministic. Filtering does not mutate the source list.

Expected stdout:

HTML, Python
HTML, Python
Python total: 45
Coordinate: 2, 3

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

sessions = [{"topic": "HTML", "minutes": 20},
            {"topic": "Python", "minutes": 30},
            {"topic": "Python", "minutes": 15}]
long_sessions = [item["topic"] for item in sessions if item["minutes"] >= 20]
topics = sorted({item["topic"] for item in sessions})
totals = {}
for item in sessions:
    topic = item["topic"]
    totals[topic] = totals.get(topic, 0) + item["minutes"]
coordinate = (2, 3)
print(", ".join(long_sessions))
print(", ".join(topics))
print(f"Python total: {totals['Python']}")
print(f"Coordinate: {coordinate[0]}, {coordinate[1]}")
Python 05 - Handle expected errors

Catch the error you expect at the boundary where recovery makes sense. An unrelated programming error should remain visible. The parser accepts the integer text formats supported by int, including signs; it is not a strict digit-only validator.

Expected stdout:

Accepted: 15
Use a non-negative whole number.
Use a non-negative whole number.

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

def parse_minutes(text):
    if not isinstance(text, str):
        raise TypeError("Expected text.")
    value = int(text.strip())
    if value < 0:
        raise ValueError("Minutes cannot be negative.")
    return value

for raw in [" 15 ", "oops", "-2"]:
    try:
        print(f"Accepted: {parse_minutes(raw)}")
    except ValueError:
        print("Use a non-negative whole number.")
Python 06 - Read and write a toy file

The file path is fixed inside a newly created toy directory, and both file handles close at the end of their with blocks. TemporaryDirectory then removes that directory. No existing document is read or overwritten. Run from a writable practice folder.

Expected stdout:

Line count: 2
First: Read one example
Temporary folder removed: True

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory(prefix="atlas-toy-", dir=".") as folder:
    path = Path(folder) / "notes.txt"
    with path.open("w", encoding="utf-8") as stream:
        stream.write("Read one example\nChange one value\n")
    with path.open("r", encoding="utf-8") as stream:
        lines = stream.read().splitlines()
    print(f"Line count: {len(lines)}")
    print(f"First: {lines[0]}")
print(f"Temporary folder removed: {not Path(folder).exists()}")
Python 07 - Round trip small JSON

JSON serializes a small data record. JSON false becomes Python False when decoded. This example handles only its own tiny string; it does not parse an external or unbounded input and does not execute JSON as code.

Expected stdout:

{"done": false, "minutes": 25, "topic": "Python"}
Same values: True
Minutes: 25

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import json

record = {"topic": "Python", "minutes": 25, "done": False}
encoded = json.dumps(record, sort_keys=True)
decoded = json.loads(encoded)
print(encoded)
print(f"Same values: {decoded == record}")
print(f"Minutes: {decoded['minutes']}")
Python 08 - Reuse a local module

Save both files in the same practice folder. The module provides a reusable function. The main guard runs the demonstration when the entry file is executed directly. Importing that entry file does not call main.

Expected stdout:

Total: 35

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

from study_tools import total_minutes

def main():
    print(f"Total: {total_minutes([10, 20, 5])}")

if __name__ == "__main__":
    main()

Companion: study_tools.py

def total_minutes(values):
    values = tuple(values)
    if any(type(value) is not int for value in values):
        raise TypeError("Use integers.")
    if any(value < 0 for value in values):
        raise ValueError("Use non-negative minutes.")
    return sum(values)
Python 09 - Test behavior with unittest

Tests compare observable behavior with a contract, including an invalid input. The suite uses a deterministic summary. A failing test changes the process exit code; proposed tests alone are not evidence that they ran.

Expected stdout:

Tests: 4; failures: 0; errors: 0

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import unittest

def square(value):
    if type(value) is not int:
        raise TypeError("Use an integer.")
    return value * value

class SquareTests(unittest.TestCase):
    def test_positive(self):
        self.assertEqual(square(3), 9)
    def test_zero(self):
        self.assertEqual(square(0), 0)
    def test_negative(self):
        self.assertEqual(square(-2), 4)
    def test_invalid(self):
        with self.assertRaises(TypeError):
            square("3")

suite = unittest.defaultTestLoader.loadTestsFromTestCase(SquareTests)
result = unittest.TestResult()
suite.run(result)
print(f"Tests: {result.testsRun}; failures: {len(result.failures)}; errors: {len(result.errors)}")
if not result.wasSuccessful():
    raise SystemExit(1)
Python Exercise A - Count study topics

Try it first: Count a list of topic strings without changing it. Ignore whitespace-only entries, normalize case and return a dictionary of counts. Test an empty list and repeated topics.

The function keeps insertion order in the dictionary and returns an empty dictionary for no topics. It expects an iterable of strings; values of other types are outside this exercise contract.

Expected stdout:

{'python': 2, 'html': 1}
{}

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

def count_topics(topics):
    counts = {}
    for topic in topics:
        normalized = topic.strip().casefold()
        if normalized:
            counts[normalized] = counts.get(normalized, 0) + 1
    return counts

print(count_topics([" Python ", "HTML", "python", " "]))
print(count_topics([]))
Python Exercise B - Recover from input errors

Try it first: Given strings representing minutes, sum valid non-negative integers and count invalid entries. Return a pair. Do not stop at the first bad string; test empty input and all-invalid input.

The exercise accepts a list of strings. Catching ValueError recovers from invalid integer text while leaving unrelated exceptions visible. Each item is accounted for as accepted or rejected.

Expected stdout:

Total: 15; rejected: 2

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

def collect_minutes(values):
    accepted = []
    rejected = 0
    for raw in values:
        try:
            number = int(raw)
            if number < 0:
                raise ValueError("Negative minutes")
        except ValueError:
            rejected += 1
        else:
            accepted.append(number)
    return sum(accepted), rejected

total, rejected = collect_minutes(["10", "bad", "-1", "5"])
print(f"Total: {total}; rejected: {rejected}")
Python Exercise C - A temporary JSON file

Try it first: Write a tiny progress dictionary as UTF-8 JSON inside a new temporary directory, read it back, print a summary and show that the directory is removed. Never use an existing file path.

The temporary directory owns the file lifecycle. The code reads only the small record it just wrote, and cleanup is observable after leaving the context.

Expected stdout:

Completed: 2
Next: functions
Cleaned up: True

Test record: passed; CPython 3.9.6; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import json
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory(prefix="atlas-json-", dir=".") as folder:
    path = Path(folder) / "progress.json"
    progress = {"completed": ["types", "loops"], "next": "functions"}
    path.write_text(json.dumps(progress), encoding="utf-8")
    restored = json.loads(path.read_text(encoding="utf-8"))
    print(f"Completed: {len(restored['completed'])}")
    print(f"Next: {restored['next']}")
print(f"Cleaned up: {not Path(folder).exists()}")
Tested learning pack

SQL Foundations

Queries, schema, joins, grouping, NULL, transactions, fixed CLI parameters and exercises. Portable concepts are distinguished from tested SQLite behavior.

Beginners who can save plain text and run an installed command-line runtime. Allow 4 to 6 hours, at your own pace.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

SQL is a language family with implementation differences. This pack executes only the installed SQLite CLI 3.54.0 on macOS 27.0.1 arm64. SELECT, WHERE, explicit joins, grouping and NULL reasoning transfer broadly, but no other engine was tested. Dot commands, PRAGMA, typeof and SQLite affinity are labeled dialect details. Open each complete .sql file with sqlite3 -batch -init /dev/null -safe :memory: followed by input redirection from its quoted filename. Each invocation gets a new disposable in-memory database; never substitute an existing database path.

1. Start with a named dialect

SQL is a language family with implementation differences. This pack executes only the installed SQLite CLI 3.54.0 on macOS 27.0.1 arm64. SELECT, WHERE, explicit joins, grouping and NULL reasoning transfer broadly, but no other engine was tested. Dot commands, PRAGMA, typeof and SQLite affinity are labeled dialect details. Open each complete .sql file with sqlite3 -batch -init /dev/null -safe :memory: followed by input redirection from its quoted filename. Each invocation gets a new disposable in-memory database; never substitute an existing database path.

2. Read a query as a question

Name the required columns, source tables, row conditions and desired order. SELECT does not promise an order without ORDER BY. Use a stable tie breaker when equal sort keys matter. Write explicit JOIN ... ON rather than a comma join, and qualify ambiguous column names with aliases. Start with tiny records whose result you can predict by hand. A query that returns no rows is different from a query that failed; keep stderr and exit status in the test record.

3. Give stored rows a contract

A primary key identifies a row, UNIQUE expresses a uniqueness rule and NOT NULL prevents absence. CHECK expresses a row condition. In SQLite ordinary type declarations give affinity rather than a universal rigid type contract. Example 02 combines an integer-affinity column with a SQLite typeof check. A nullable CHECK alone does not reject NULL; use NOT NULL when required. Foreign-key declarations need enforcement enabled per SQLite connection, outside an active transaction.

4. Treat missing values deliberately

NULL is not zero or empty text. Use IS NULL or IS NOT NULL for presence tests. Many comparisons with NULL produce unknown and are not retained by WHERE. COUNT(*) includes all rows, while COUNT(expression) ignores NULL results. SUM of no non-NULL inputs returns NULL. Choose COALESCE only when the replacement has a stated meaning. NOT EXISTS is useful for missing relationships; NOT IN behaves differently if its candidate set includes NULL.

5. Join first, then count the right thing

INNER JOIN retains matching pairs; LEFT JOIN also retains unmatched rows from the left. One-to-many matches can multiply rows and inflate totals if you join several child tables at once. Count the child primary key for zero-on-no-match summaries. A right-table predicate in WHERE may remove the unmatched rows you wanted to keep; placing a matching condition in ON has different semantics. Test an unmatched parent and multiple matches before trusting an aggregate.

6. Group and name intermediate results

WHERE filters before aggregation; HAVING filters groups. List non-aggregate output columns in GROUP BY rather than depending on SQLite bare-column behavior. An ordinary WITH clause can name a summary for the current statement. CASE makes a result choice visible. These tools make a query understandable, but readability does not prove performance. Index selection, query plans, recursive CTEs and window functions remain later topics.

7. Transactions need explicit outcomes

BEGIN groups changes until COMMIT or ROLLBACK. This pack rehearses updates and reversals only in memory. Keep a specific WHERE predicate and inspect affected state. An SQL error does not always abort the entire transaction; handle failure deliberately in application code. SQLite permits only one simultaneous writer, and transaction behavior and isolation differ between engines. Nested BEGIN is not a nesting mechanism; savepoints are a later topic.

8. Separate values from SQL structure

Bind external values through the application driver instead of concatenating them into SQL text. Parameters represent literal values, not identifiers or keywords; choose identifiers from an allowlist in a real application. Example 07 uses only fixed authored CLI literals. SQLite .parameter set evaluates its value as an expression before fallback handling, so it is not a safe string-input API. The quote-shaped toy shows bound-query behavior, not an application security certification. Test constraints, NULL, missing rows and rollback as well as happy paths.

Quick reference

Query

SELECT columns FROM table

Name the output and its source.

Filter

WHERE condition

Keep rows whose condition is true.

Order

ORDER BY key, id

Specify deterministic ordering.

Schema

PRIMARY KEY / UNIQUE

Identity and uniqueness rules.

Schema

NOT NULL / CHECK

Presence and row-condition constraints.

SQLite

typeof(value)

SQLite storage-class inspection, not portable SQL.

Missing

IS NULL / IS NOT NULL

Test absence explicitly.

Missing

COALESCE(value, fallback)

Choose a meaningful fallback.

Join

JOIN ... ON / LEFT JOIN

Matching pairs / retain unmatched left rows.

Aggregate

COUNT(*) / COUNT(column)

Rows / non-NULL column values.

Aggregate

GROUP BY / HAVING

Form and filter group summaries.

Query

WITH name AS (...)

Name a statement-scoped query step.

Query

CASE WHEN ... THEN ... ELSE ... END

Compute a conditional result.

Query

EXISTS / NOT EXISTS

Test whether matching rows exist.

Transaction

BEGIN / COMMIT / ROLLBACK

Group, keep or reverse a toy change.

Parameters

:minimum / driver binding API

Bind values; CLI .parameter is a separate expression parser.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

SQL 01 Filter and order

WHERE chooses rows; ORDER BY defines the displayed order, including a tie breaker. These clauses transfer broadly, but this complete file uses SQLite CLI dot commands. Every file starts with its own data.

Expected stdout:

SQL|30
HTML|20

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE sessions (id INTEGER PRIMARY KEY, topic TEXT, minutes INTEGER);
INSERT INTO sessions VALUES (1,'HTML',20),(2,'SQL',30),(3,'SQL',10);
SELECT topic, minutes FROM sessions
WHERE minutes >= 20 ORDER BY minutes DESC, id;
SQL 02 Define a contract

Keys identify rows, UNIQUE rejects duplicate names and NOT NULL rejects absence. SQLite affinity alone is not a rigid type contract: typeof in this CHECK is SQLite-specific. This is not portable schema DDL.

Expected stdout:

1|SQL|25
2|Shell|0

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE topics (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE,
  minutes INTEGER NOT NULL CHECK (typeof(minutes) = 'integer' AND minutes >= 0)
);
INSERT INTO topics VALUES (1,'SQL',25),(2,'Shell',0);
SELECT id, name, minutes FROM topics ORDER BY id;
SQL 03 Reason about NULL

NULL represents a missing value. Equality with NULL does not become true; use IS NULL. COUNT(*) counts rows, COUNT(column) counts non-NULL values. COALESCE here uses -1 only as a display marker, not a stored replacement.

Expected stdout:

3|2|10
1|10
2|-1
3|0
0
1

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE notes (id INTEGER PRIMARY KEY, minutes INTEGER);
INSERT INTO notes VALUES (1,10),(2,NULL),(3,0);
SELECT COUNT(*), COUNT(minutes), SUM(minutes) FROM notes;
SELECT id, COALESCE(minutes, -1) FROM notes ORDER BY id;
SELECT COUNT(*) FROM notes WHERE minutes = NULL;
SELECT COUNT(*) FROM notes WHERE minutes IS NULL;
SQL 04 Keep unmatched topics

LEFT JOIN keeps each topic even without a session. Count the non-null child key rather than COUNT(*) to show zero for an unmatched row. A right-side filter in WHERE can remove unmatched rows. PRAGMA foreign_keys is SQLite-specific and set before writes.

Expected stdout:

SQL|2|30
Shell|1|15
Python|0|0

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
PRAGMA foreign_keys = ON;
CREATE TABLE topics (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE sessions (id INTEGER PRIMARY KEY,
  topic_id INTEGER NOT NULL REFERENCES topics(id), minutes INTEGER NOT NULL);
INSERT INTO topics VALUES (1,'SQL'),(2,'Shell'),(3,'Python');
INSERT INTO sessions VALUES (1,1,20),(2,1,10),(3,2,15);
SELECT t.name, COUNT(s.id), COALESCE(SUM(s.minutes),0)
FROM topics AS t LEFT JOIN sessions AS s ON s.topic_id = t.id
GROUP BY t.id, t.name ORDER BY t.id;
SQL 05 Aggregate and filter groups

WHERE filters input rows, GROUP BY forms groups and HAVING filters group results. Every selected non-aggregate column appears in GROUP BY; avoid SQLite bare-column shortcuts when writing queries meant to transfer.

Expected stdout:

SQL|2|35

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE sessions (topic TEXT NOT NULL, minutes INTEGER NOT NULL);
INSERT INTO sessions VALUES ('SQL',20),('SQL',15),('Shell',10);
SELECT topic, COUNT(*), SUM(minutes) AS total
FROM sessions WHERE minutes > 0
GROUP BY topic HAVING SUM(minutes) >= 30 ORDER BY topic;
SQL 06 Commit and roll back

Run only in the new in-memory database. The first change is undone; the second persists for this connection. The explicit key predicate limits the update. Do not assume every statement error rolls back a whole transaction; applications must handle errors and rollback deliberately.

Expected stdout:

rolled back|10
committed|15
unchanged|20

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE progress (id INTEGER PRIMARY KEY, minutes INTEGER NOT NULL);
INSERT INTO progress VALUES (1,10),(2,20);
BEGIN;
UPDATE progress SET minutes = minutes + 5 WHERE id = 1;
ROLLBACK;
SELECT 'rolled back', minutes FROM progress WHERE id = 1;
BEGIN;
UPDATE progress SET minutes = minutes + 5 WHERE id = 1;
COMMIT;
SELECT 'committed', minutes FROM progress WHERE id = 1;
SELECT 'unchanged', minutes FROM progress WHERE id = 2;
SQL 07 Bind fixed toy values

The statement uses bound values, including a fixed quote-shaped string that stays data. The CLI .parameter set command itself evaluates SQL expressions; never construct it from untrusted text. In applications use the driver binding API with a fixed SQL statement. Placeholders cannot stand for table names or keywords.

Expected stdout:

SQL
0
x' OR 1=1 --

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE topics (name TEXT NOT NULL, minutes INTEGER NOT NULL);
INSERT INTO topics VALUES ('SQL',30),('Shell',20);
.parameter init
.parameter set :minimum 25
SELECT name FROM topics WHERE minutes >= :minimum ORDER BY name;
.parameter set :topic "'x'' OR 1=1 --'"
SELECT COUNT(*) FROM topics WHERE name = :topic;
SELECT :topic;
SQL 08 Name a query step

An ordinary CTE names an intermediate query for one statement. CASE expresses a result choice. Neither is a persistent table here; a CTE is a readability tool, not a promise of a faster query.

Expected stdout:

SQL|35|ready
Shell|10|practice

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE sessions (topic TEXT, minutes INTEGER);
INSERT INTO sessions VALUES ('SQL',20),('SQL',15),('Shell',10);
WITH totals AS (
  SELECT topic, SUM(minutes) AS minutes FROM sessions GROUP BY topic
)
SELECT topic, minutes,
  CASE WHEN minutes >= 30 THEN 'ready' ELSE 'practice' END AS next_step
FROM totals ORDER BY topic;
SQL 09 Find missing relationships

NOT EXISTS tests whether a matching row exists. This deliberately includes a NULL in the child table: a NOT IN subquery containing NULL has different three-valued logic and can surprise beginners.

Expected stdout:

Shell

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE topics (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions (topic_id INTEGER);
INSERT INTO topics VALUES (1,'SQL'),(2,'Shell');
INSERT INTO sessions VALUES (1),(NULL);
SELECT name FROM topics AS t
WHERE NOT EXISTS (SELECT 1 FROM sessions AS s WHERE s.topic_id = t.id)
ORDER BY name;
SQL Exercise A Count all topics

Try it first: Return every topic and its session count, including zero. Sort names. Test a topic with no sessions.

Count a non-null child key and group by the parent identity as well as its name. This keeps the topic with no sessions.

Expected stdout:

SQL|2
Shell|0

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE topics (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions (id INTEGER PRIMARY KEY, topic_id INTEGER);
INSERT INTO topics VALUES (1,'SQL'),(2,'Shell');
INSERT INTO sessions VALUES (1,1),(2,1);
SELECT t.name, COUNT(s.id) FROM topics AS t
LEFT JOIN sessions AS s ON s.topic_id = t.id
GROUP BY t.id, t.name ORDER BY t.name;
SQL Exercise B Preserve unknown minutes

Try it first: Summarize row count, known count, unknown count and known-minute total without turning unknown into zero.

Zero is a known value; NULL is unknown. The total summarizes only the known values and must not be described as the complete total.

Expected stdout:

3|2|1|15

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE sessions (id INTEGER PRIMARY KEY, minutes INTEGER);
INSERT INTO sessions VALUES (1,0),(2,NULL),(3,15);
SELECT COUNT(*) AS rows, COUNT(minutes) AS known,
  COUNT(*) - COUNT(minutes) AS unknown,
  SUM(minutes) AS known_total FROM sessions;
SQL Exercise C Rehearse a change

Try it first: Change one toy row inside a transaction, display it, roll back and prove the original value remains.

The preview is a reversible transaction in an isolated in-memory toy database, not a production change plan.

Expected stdout:

preview|25
restored|20

Test record: passed; SQLite CLI 3.54.0; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE progress (id INTEGER PRIMARY KEY, minutes INTEGER CHECK(minutes >= 0));
INSERT INTO progress VALUES (1,20);
BEGIN;
UPDATE progress SET minutes = 25 WHERE id = 1;
SELECT 'preview', minutes FROM progress WHERE id = 1;
ROLLBACK;
SELECT 'restored', minutes FROM progress WHERE id = 1;
Tested learning pack

Shell Foundations

Quoting, pipes, status, toy files, loops, functions and safe automation patterns. POSIX-style syntax, Bash 3.2 and native Zsh are distinguished.

Beginners who can save plain text and run an installed command-line runtime. Allow 4 to 6 hours, at your own pace.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

The terminal is an interface; sh, Bash and Zsh interpret command text. This pack tests macOS /bin/sh (selecting Bash 3.2.57), /bin/bash 3.2.57 and /bin/zsh 5.9. POSIX-style examples use a conservative shared syntax subset; Bash and Zsh examples name their extensions. Run scripts using the stated interpreter and a quoted filename; executable permission is unnecessary. A shebang documents the intended interpreter when a script is launched directly, but an explicit shell command chooses the interpreter regardless of the shebang.

1. A shell is an interpreter, not a terminal

The terminal is an interface; sh, Bash and Zsh interpret command text. This pack tests macOS /bin/sh (selecting Bash 3.2.57), /bin/bash 3.2.57 and /bin/zsh 5.9. POSIX-style examples use a conservative shared syntax subset; Bash and Zsh examples name their extensions. Run scripts using the stated interpreter and a quoted filename; executable permission is unnecessary. A shebang documents the intended interpreter when a script is launched directly, but an explicit shell command chooses the interpreter regardless of the shebang.

2. Preserve data as arguments

Shell parsing, expansion and argument construction happen before a command runs. Use single quotes for fixed literal text and double quotes around variable expansions. Use "$@" to pass positional arguments individually. A wildcard stored in quoted data stays text. Avoid eval, command strings and sourcing untrusted files. printf with a fixed format is more predictable than treating user text as the format. Names with spaces, leading dashes or newlines need deliberate treatment; these exercises never use arguments as arbitrary file paths.

3. Make failures observable

An exit status of zero means success; nonzero meanings depend on the command. Inspect $? immediately or put the command in an if condition. && runs its right side after success; || runs its right side after failure. stderr is separate from stdout. Do not assume set -e provides complete error handling: context changes its behavior. Script checks here record stdout, stderr and exit status, including invalid inputs. A syntax check catches parse errors, not incorrect behavior.

4. Pipes need a status policy

A pipeline connects stdout to the next command. Without pipefail its status comes from the final command, so a failed earlier command can be hidden. Bash and Zsh support pipefail but differ in syntax and other behaviors. POSIX.1-2024 includes pipefail; older portability targets do not. This pack keeps the shared example at default behavior and labels dialect-specific checks. Avoid relying on a variable assigned inside a piped loop remaining visible outside it; shells differ. Feed a current-shell loop with redirection or a here-document.

5. File practice owns a small new directory

Redirection can overwrite files before a command runs. The file examples use macOS mktemp -d with a template under the current writable practice directory, umask 077 and fixed filenames inside the new directory. mktemp is a platform utility and not claimed as universal POSIX tooling. Only files created by the example are read. The scripts retain toy folders for inspection and contain no deletion commands. The harness removes only its own outer temporary directory. Never substitute a real document path.

6. Read and loop without losing text

IFS= read -r preserves leading/trailing whitespace and backslashes in a line. The examples use fixed newline-terminated text; a general arbitrary-file reader also needs a policy for a final line without a newline and cannot treat NUL-delimited data as ordinary shell strings. A quoted here-document delimiter suppresses expansion in its body. A for loop over positional parameters keeps argument boundaries. Bound while loops with validated inputs and test zero, maximum and invalid cases.

7. Functions and dialect boundaries

A shell function can communicate success through return and text through stdout. Prefer small functions with explicit input contracts. Bash 3.2 has zero-based indexed arrays but no associative arrays. Native Zsh arrays usually start at one, and its scalar splitting and glob defaults differ. Shell options can alter these behaviors, so the Zsh example uses emulate to establish native mode. The portable examples avoid arrays, [[ ... ]], local and shell-specific substitutions; passing three invocation modes across two implementations is evidence, not a standards certificate.

8. Build automation with a dry run first

Separate deciding from doing. Default to a printed plan, accept only documented modes, validate inputs before arithmetic or file access, and stop when creating the toy directory fails. The explicit write mode creates only a new fixed report. No cron jobs, network commands, permission changes or production integrations are included. Run tests with an empty controlled environment and a small PATH. Timeouts and a fresh directory bound trusted teaching examples; they are not a sandbox for arbitrary downloaded shell code.

Quick reference

Quoting

'literal' / "$value"

Literal text / one expanded argument.

Arguments

"$@" / "$#"

Separate arguments / argument count.

Output

printf '%s\n' "$value"

Use a fixed format for text.

Status

if command; then ...; else ...; fi

Handle success and failure explicitly.

Status

$? / return / exit

Previous status / function outcome / process outcome.

Flow

&& / ||

Continue after success / failure.

Streams

producer | consumer

Connect stdout; decide how failures propagate.

Streams

> / >> / 2>

Overwrite / append / redirect stderr; paths have effects.

Input

IFS= read -r line

Preserve whitespace and backslashes.

Flow

for item do ... done

Iterate over positional arguments.

Flow

case "$value" in ... esac

Match a small allowed input set.

Functions

name() { ...; }

Define a reusable shell operation.

Files

mktemp -d './atlas-shell.XXXXXX'

macOS utility: create a new local toy folder.

Bash

array=(...); "${array[0]}"

Bash indexed arrays start at zero.

Zsh

emulate -L zsh; "${array[1]}"

Native Zsh mode; first array element is one.

Safety

--dry-run / --write-toy

Example-specific allowlisted modes, not universal command flags.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Shell 01 Preserve argument boundaries

Single quotes hold literal text; double quotes preserve an expanded value as one argument. Quoting data does not execute the characters stored in it. Use a fixed printf format. The empty argument is retained.

Expected stdout:

Topic: SQL and Shell
Literal: *.txt; $(not_a_command)
Arguments: 3

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
topic='SQL and Shell'
literal='*.txt; $(not_a_command)'
printf 'Topic: %s\n' "$topic"
printf 'Literal: %s\n' "$literal"
set -- "$topic" "$literal" ''
printf 'Arguments: %s\n' "$#"
Shell 02 Inspect exit status

Zero means success; nonzero denotes failure or another documented outcome. Save $? immediately. This example handles a known failure in if instead of relying on set -e, whose contextual rules can surprise learners.

Expected stdout:

Handled status: 1
Continue deliberately

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
if false; then
  printf '%s\n' 'Unexpected success'
else
  result=$?
  printf 'Handled status: %s\n' "$result"
fi
printf '%s\n' 'Continue deliberately'
Shell 03 Transform a tiny stream

A pipe sends stdout to the next command. Sorting groups duplicates for uniq. With pipefail disabled, the final command determines the status; the failed first command is hidden here. Older POSIX shell targets do not promise pipefail; POSIX.1-2024 adds it, while installed-runtime support still needs checking.

Expected stdout:

alpha
beta
Default pipeline status: 0

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
printf '%s\n' beta alpha beta | LC_ALL=C sort | uniq
false | cat
result=$?
printf 'Default pipeline status: %s\n' "$result"
Shell 04 Write only a new toy file

macOS mktemp creates a new directory inside the writable practice folder. Its utility syntax is platform-specific. Fixed names inside that new directory cannot overwrite a previous document. IFS= read -r preserves spaces and backslashes. No deletion command is included; the test harness cleans its own outer directory.

Expected stdout:

Line 1: Read one example
Line 2: Change one value
Lines: 2
Toy folder retained for inspection.

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
umask 077
toy_dir=$(mktemp -d './atlas-shell.XXXXXX') || exit 1
printf '%s\n' 'Read one example' 'Change one value' > "$toy_dir/notes.txt" || exit 1
count=0
while IFS= read -r line; do
  count=$((count + 1))
  printf 'Line %s: %s\n' "$count" "$line"
done < "$toy_dir/notes.txt"
printf 'Lines: %s\n' "$count"
printf '%s\n' 'Toy folder retained for inspection.'
Shell 05 Loop over quoted values

The for loop without an in-list visits positional parameters as separate values. Arithmetic is used only on an internal counter. Do not feed untrusted strings into shell arithmetic or turn command text into code.

Expected stdout:

1: SQL basics
2: Shell basics
3: Python basics
Visited: 3

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
set -- 'SQL basics' 'Shell basics' 'Python basics'
count=0
for topic do
  count=$((count + 1))
  printf '%s: %s\n' "$count" "$topic"
done
printf 'Visited: %s\n' "$count"
Shell 06 Validate with a function

The function returns a status, not a text result. The allowlist accepts a deliberately small ASCII token. It is a demonstration contract, not a universal filename sanitizer. No path is opened.

Expected stdout:

Accepted: <sql_01>
Rejected: <two words>
Rejected: <>
Rejected: <../notes>
Rejected: <é>
Rejected: <Ä>

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
valid_topic() {
  case "$1" in
    ''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-]*) return 1 ;;
    *) return 0 ;;
  esac
}
for candidate in 'sql_01' 'two words' '' '../notes' 'é' 'Ä'; do
  if valid_topic "$candidate"; then
    printf 'Accepted: <%s>\n' "$candidate"
  else
    printf 'Rejected: <%s>\n' "$candidate"
  fi
done
Shell 07 Default to a dry run

No argument previews the operation. An explicit allowlisted mode creates one fixed report inside a new toy directory. Invalid modes fail before a write. This is a safe teaching pattern, not a scheduler or production automation system.

Expected stdout:

Would create a new toy report.

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
mode=${1---dry-run}
case "$mode" in
  --dry-run) printf '%s\n' 'Would create a new toy report.' ;;
  --write-toy)
    umask 077
    toy_dir=$(mktemp -d './atlas-shell.XXXXXX') || exit 1
    printf '%s\n' 'Study: SQL and Shell' > "$toy_dir/report.txt" || exit 1
    printf '%s\n' 'Created one new toy report; folder retained.' ;;
  *) printf '%s\n' 'Use --dry-run or --write-toy.' >&2; exit 2 ;;
esac
Shell 08 Use Bash features explicitly

Run with Bash 3.2.57, not sh. Indexed arrays are zero-based, and quoted array expansion preserves each element. This old Bash lacks modern associative arrays. pipefail exposes the failed producer in this example.

Expected stdout:

First: SQL basics
Count: 2
<SQL basics>
<Shell basics>
Bash pipeline status: 1

Test record: passed; Bash 3.2.57; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/bash
topics=('SQL basics' 'Shell basics')
printf 'First: %s\n' "${topics[0]}"
printf 'Count: %s\n' "${#topics[@]}"
for topic in "${topics[@]}"; do printf '<%s>\n' "$topic"; done
set -o pipefail
if false | cat; then
  printf '%s\n' 'Unexpected success'
else
  printf 'Bash pipeline status: %s\n' "$?"
fi
Shell 09 Use native Zsh deliberately

Native Zsh normally indexes arrays from one. emulate establishes the intended option mode. Default unquoted scalar splitting and unmatched glob behavior differ from Bash; these examples quote values and avoid ambiguous globbing. Use the named interpreter.

Expected stdout:

First: SQL basics
Count: 2
<SQL basics>
<Shell basics>
Zsh pipeline status: 1

Test record: passed; Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/zsh
emulate -L zsh
topics=('SQL basics' 'Shell basics')
printf 'First: %s\n' "${topics[1]}"
printf 'Count: %s\n' "${#topics[@]}"
for topic in "${topics[@]}"; do printf '<%s>\n' "$topic"; done
setopt PIPE_FAIL
if false | cat; then
  printf '%s\n' 'Unexpected success'
else
  printf 'Zsh pipeline status: %s\n' "$?"
fi
Shell Exercise A Keep every argument

Try it first: Print each argument and a count, preserving spaces, empty strings and wildcard characters. With no arguments use the three toy values.

No-argument mode supplies three toy values; explicit arguments are kept exactly as separate strings. The wildcard is printed literally.

Expected stdout:

1: <SQL basics>
2: <*.txt>
3: <>
Arguments: 3

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
if [ "$#" -eq 0 ]; then set -- 'SQL basics' '*.txt' ''; fi
count=0
for item do
  count=$((count + 1))
  printf '%s: <%s>\n' "$count" "$item"
done
printf 'Arguments: %s\n' "$count"
Shell Exercise B Count literal lines

Try it first: Count nonempty lines from literal toy input while preserving leading/trailing spaces and backslashes. Keep the final count outside the loop.

A quoted here-document supplies fixed literal input. The loop stays in the current shell and preserves its counter. Empty means zero characters here; a whitespace-only line would count.

Expected stdout:

<SQL basics>
<  keep spaces  >
<literal\backslash>
Nonempty lines: 3

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
count=0
while IFS= read -r line; do
  case "$line" in '') continue ;; esac
  count=$((count + 1))
  printf '<%s>\n' "$line"
done <<'LESSON_TEXT'
SQL basics

  keep spaces  
literal\backslash
LESSON_TEXT
printf 'Nonempty lines: %s\n' "$count"
Shell Exercise C Bound a small loop

Try it first: Accept only one digit from 0 to 5, default to 3, print that many steps and a summary. Reject every other argument before the loop.

An exact allowlist bounds the loop before numeric comparison. It rejects negative, large, empty and expression-shaped inputs. This avoids arithmetic interpretation of arbitrary text.

Expected stdout:

Practice 1
Practice 2
Practice 3
Completed: 3

Test record: passed; macOS sh (Bash 3.2.57) / Bash 3.2.57 / Zsh 5.9; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#!/bin/sh
requested=${1-3}
case "$requested" in
  0|1|2|3|4|5) ;;
  *) printf '%s\n' 'Use one digit from 0 to 5.' >&2; exit 2 ;;
esac
count=0
while [ "$count" -lt "$requested" ]; do
  count=$((count + 1))
  printf 'Practice %s\n' "$count"
done
printf 'Completed: %s\n' "$count"
Tested learning pack

TypeScript Foundations

Types, unions, narrowing, functions, objects, collections, runtime checks, discriminated unions, generics and local modules. Introductory static and runtime coverage only.

Learners familiar with the Web Foundations JavaScript examples. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Compiler: /usr/local/lib/node_modules/openclaw/node_modules/typescript/lib/tsc.js (6.0.3), invoked with installed Node 24.18.0. It is bundled with an existing package and is not on PATH. No package manager was run. Use the supplied tsconfig.json and package.json in a fresh practice directory, with one entry example and any companion. Check with node followed by the quoted compiler path and --project . --noEmit; emit with the same command without --noEmit; run the emitted .js with node. The browser exports source text only. See README for exact commands and limits.

Configuration: tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "Node16",
    "moduleResolution": "Node16",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noEmitOnError": true,
    "types": [],
    "lib": [
      "ES2020",
      "DOM"
    ]
  },
  "include": [
    "*.ts"
  ]
}
Configuration: package.json
{"type":"commonjs"}

1. Types and execution

TypeScript checks source before execution. Node runs the emitted JavaScript separately. Passing one stage does not prove the other; annotations are erased and do not validate incoming JSON. These examples use TypeScript 6.0.3 and Node 24.18.0, not Node type stripping.

2. A reproducible compiler contract

The included tsconfig enables strict, noUncheckedIndexedAccess and exactOptionalPropertyTypes, with ES2020 and Node16 module resolution. types: [] prevents ambient packages from changing the exercise. DOM declarations are included here for console typing; they also declare browser APIs that Node does not supply. Use the installed compiler path recorded in the toolchain evidence.

3. Values, functions and collections

Start with inference and annotate public contracts where useful. Unions describe alternatives. readonly parameters restrict mutations through that reference. Empty arrays and missing keys need explicit outcomes; defaults should preserve zero and false.

4. Objects and absence

An optional property can be absent. The exact optional flag distinguishes absence from explicitly writing undefined unless undefined is part of its declared type. readonly is a static restriction rather than a runtime freeze or an ownership system.

5. Narrowing and runtime validation

Use typeof, null checks and discriminators to narrow unions. unknown requires a check before use; any bypasses useful checks. JSON.parse can return anything and a cast only changes what the compiler believes. Bound inputs before parsing, then validate the application contract.

6. Errors and exhaustiveness

An error diagnostic is a static result, while a thrown Error is a runtime event. catch values are unknown under strict checking. A never assignment can reveal a missing branch in a discriminated union. noEmitOnError must be enabled to prevent output after compiler errors.

7. Generics and local modules

Generics preserve relationships between types rather than providing runtime introspection. A local module exports a value and imports it by a path. Module settings, filename suffixes and package.json determine emitted behavior; this pack deliberately fixes one CommonJS configuration.

8. Practice and limits

Run each example in its own folder with its companions and the supplied config. First check with --noEmit, then emit only after checks pass and run the corresponding .js file. Expected failures are kept in source JSON and the test evidence. No JSX, frameworks, package installation, deployment, advanced type metaprogramming or cross-platform claim is included.

Quick reference

Values

const count: number = 2

Annotation or inference constrains assignments.

Union

string | number

Check the active case before case-specific methods.

Function

(x: number): number

Types describe parameter and return contracts.

Collection

readonly number[]

Restricts writes through this reference.

Optional

minutes?: number

May be absent; explicit undefined depends on flags/type.

Default

value ?? fallback

Uses fallback only for null or undefined.

Index

Record<string, number>

Unknown keys need checking with the chosen flags.

Unknown

value: unknown

Requires narrowing before use.

Guard

typeof value === "string"

Runtime test that narrows a static type.

Discriminator

kind: "ok" | "error"

Literal tags can identify object variants.

Exhaustiveness

const impossible: never = value

Unhandled cases become type errors.

Generic

function first<T>(xs: T[])

Relates input and output types.

Module

import {x} from "./module.js"

Resolves .ts source and names emitted .js output here.

Static check

node <compiler> --project . --noEmit

Checks only; no JavaScript execution.

Emit

noEmitOnError: true

Suppresses output on compiler diagnostics.

Run

node "Example.js"

Executes emitted code; does not perform typechecking.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

TypeScript 01 - Values and inference

Annotations constrain assignments; inference also records a type. typeof here is a JavaScript runtime operation. Type annotations disappear from emitted JavaScript.

Expected stdout:

Ada: 25 minutes
true number

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

const learnerName: string = "Ada";
const minutes = 25;
const ready: boolean = minutes > 0;
console.log(`${learnerName}: ${minutes} minutes`);
console.log(ready, typeof minutes);
TypeScript 02 - Narrow a union

A typeof guard narrows each branch. No assertion or any is needed.

Expected stdout:

NOTES
2.5

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

function label(value: string | number): string {
  return typeof value === "string"
    ? value.trim().toUpperCase() : value.toFixed(1);
}
console.log(label("  notes "));
console.log(label(2.5));
TypeScript 03 - Function contracts

readonly describes this function parameter; it is not a deep runtime freeze. The initial accumulator handles an empty list.

Expected stdout:

35
0

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

function total(values: readonly number[], bonus = 0): number {
  return values.reduce((sum, value) => sum + value, bonus);
}
console.log(total([10, 20], 5));
console.log(total([]));
TypeScript 04 - Optional object fields

With exactOptionalPropertyTypes, an absent minutes field differs from explicitly supplying undefined. readonly checks assignment through this type, not mutation by all possible aliases.

Expected stdout:

Read: 0
Practice: 20

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

type Note = { readonly title: string; minutes?: number };
function describe(note: Note): string {
  return `${note.title}: ${note.minutes ?? 0}`;
}
console.log(describe({title: "Read"}));
console.log(describe({title: "Practice", minutes: 20}));
TypeScript 05 - Missing indexed values

noUncheckedIndexedAccess makes uncertain index results include undefined. Nullish defaults preserve legitimate zero values.

Expected stdout:

20
0
empty

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

const minutes: Record<string, number> = {read: 20};
const first: number[] = [];
console.log(minutes["read"] ?? 0);
console.log(minutes["missing"] ?? 0);
console.log(first[0] ?? "empty");
TypeScript 06 - Check runtime data

Assign untrusted-shaped values to unknown and check the runtime contract. This toy accepts extra keys and fractional nonnegative minutes; it is not JSON Schema validation. Type assertions would not validate input.

Expected stdout:

15
invalid minutes

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

function minutes(value: unknown): number {
  if (typeof value !== "object" || value === null ||
      !("minutes" in value) ||
      typeof value.minutes !== "number" ||
      !Number.isFinite(value.minutes) || value.minutes < 0) {
    throw new Error("invalid minutes");
  }
  return value.minutes;
}
const raw: unknown = JSON.parse('{"minutes":15}');
console.log(minutes(raw));
try { minutes({minutes: "15"}); }
catch (error) {
  console.log(error instanceof Error ? error.message : "error");
}
TypeScript 07 - Discriminated results

A literal discriminator narrows the object. The never assignment makes a newly added, unhandled variant a compile-time error.

Expected stdout:

Value: 3
Error: missing

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

type Result = {kind: "ok"; value: number} |
              {kind: "error"; message: string};
function show(result: Result): string {
  switch (result.kind) {
    case "ok": return `Value: ${result.value}`;
    case "error": return `Error: ${result.message}`;
    default: {
      const impossible: never = result;
      return impossible;
    }
  }
}
console.log(show({kind: "ok", value: 3}));
console.log(show({kind: "error", message: "missing"}));
TypeScript 08 - Preserve a type relationship

The generic relates the input element type to the output. It does not invent a value when the collection is empty.

Expected stdout:

alpha
empty

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

function first<T>(items: readonly T[]): T | undefined {
  return items[0];
}
console.log(first(["alpha", "beta"]) ?? "empty");
console.log(first<number>([]) ?? "empty");
TypeScript 09 - A local module

Keep the companion beside the entry file. The .js import matches the emitted file; Node16 resolution finds its .ts source for checking. The supplied package.json selects CommonJS output; no package download is involved.

Expected stdout:

12

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import { double } from "./Atlas math.js";
console.log(double(6));

Companion: Atlas math.ts

export function double(value: number): number {
  return value * 2;
}
TypeScript exercise A - A safe average

Try it first: Write average for a finite-number array. Return undefined for an empty array and display a useful fallback.

A union return type forces the caller to account for an empty input. The finite-number requirement remains the caller contract.

Expected stdout:

15
empty

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

function average(values: readonly number[]): number | undefined {
  if (values.length === 0) return undefined;
  return values.reduce((sum, n) => sum + n, 0) / values.length;
}
console.log(average([10, 20]) ?? "empty");
console.log(average([]) ?? "empty");
TypeScript exercise B - Validate a label

Try it first: Accept unknown, return a trimmed nonblank string, and reject whitespace-only or non-string inputs.

Validation is runtime code and survives compilation. It checks type and nonblank content, not a universal naming policy.

Expected stdout:

Practice
label required
label required

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

function label(value: unknown): string {
  if (typeof value !== "string" || value.trim().length === 0) {
    throw new Error("label required");
  }
  return value.trim();
}
for (const value of ["  Practice ", " ", 7]) {
  try { console.log(label(value)); }
  catch (error) {
    console.log(error instanceof Error ? error.message : "error");
  }
}
TypeScript exercise C - Summarize a tagged task

Try it first: Use a union so an open task cannot require minutes. Display both states without any or type assertions.

The shared discriminator gives access to minutes only in the done branch.

Expected stdout:

Read: open
Code: 30 minutes

Test record: passed; TypeScript 6.0.3 static check and emit; Node 24.18.0 JavaScript execution; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

type Task = {state: "open"; title: string} |
            {state: "done"; title: string; minutes: number};
function summary(task: Task): string {
  return task.state === "done"
    ? `${task.title}: ${task.minutes} minutes`
    : `${task.title}: open`;
}
console.log(summary({state: "open", title: "Read"}));
console.log(summary({state: "done", title: "Code", minutes: 30}));
Tested learning pack

Data Formats Foundations

JSON, CSV/TSV, XML and TOML reading, serialization where supported, explicit encoding, escaping, dialects, syntax errors and small hand-written contracts. No schema engine, external files or untrusted XML parsing.

Learners comfortable with the Python Foundations examples. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Run each .py with the installed Python interpreter. Tests use CPython 3.9.6, which is unsupported upstream. JSON, CSV and XML use the standard library. TOML uses the already installed pip._vendor.tomli 1.0.3 fallback; this private API may change or disappear and is not a stable public pip interface. The preferred tomllib branch requires an already installed Python 3.11+ and is not tested here. No dependency is installed. XML examples are limited to tiny trusted authored strings; do not reuse their entry points for untrusted XML.

1. Formats are not programming languages

JSON and CSV/TSV are data formats, TOML is a configuration format, and XML is a markup language. Parsers turn text into values or trees; they do not automatically enforce an application schema. JSON Schema and XML Schema remain planned registry entries.

2. Encoding and resource bounds

Agree on UTF-8 at file boundaries and use strict decoding; do not silently replace invalid bytes. Keep examples tiny and in memory. Apply byte, row and value limits before expensive processing where possible. Limits in these toys do not make an arbitrary deeply nested or malicious document safe.

3. JSON syntax and policy

JSON values include objects, arrays, strings, numbers, booleans and null. Use serializers for escaping; do not build JSON by string concatenation. Python defaults accept NaN and repeated object names, so a stricter contract can reject both with hooks. Reject nonfinite values before encoding; huge JSON numeric exponents also need finite-value checks after decoding.

4. CSV and TSV dialects

A delimiter alone is not a complete dialect. Specify quoting, escaping, line endings, headers and encoding. Do not split lines on commas or tabs when quoted fields may contain those characters. Parse first, then check row width and convert selected cells. Do not infer a schema just because a numeric-looking cell parses.

5. Safe export boundaries

CSV writers quote delimiters and line breaks; this prevents structural corruption, not spreadsheet formula execution. Values beginning with formula-like characters require a destination-specific reviewed export policy before spreadsheet use. No spreadsheet is opened by the examples. JSON, XML and CSV need their own serializers; escaping is context-specific.

6. XML trees and trust

XML well-formedness, namespaces and application structure are different checks. Build elements and assign text instead of splicing markup. ElementTree is not hardened for malicious XML; this pack only parses tiny authored strings and never accepts untrusted XML files, DTDs or entity definitions. Installing a hardened parser is outside this task.

7. TOML configuration

TOML 1.0 has tables, arrays, strings, booleans, numbers and date/time values. Keys cannot be defined twice. A parser returns typed values; it does not enforce required application settings. Date/time values may need explicit conversion when moving into JSON. The examples use a small subset and do not test TOML 1.1 or writing TOML.

8. Error handling and schema boundaries

Catch the relevant parser error and validate the resulting values separately. Our hand-written contracts are narrow educational checks, not a JSON Schema or XSD engine. Python 3.9.6 and its private pip-vendored Tomli fallback are installed test constraints, not deployment recommendations. Use only authored local examples; all other runtimes remain untested.

Quick reference

Encoding

text.encode("utf-8")

Converts text to bytes; record the encoding.

JSON read

json.loads(text)

Parses syntax; add policy and contract checks.

JSON write

json.dumps(value, allow_nan=False)

Rejects nonfinite numbers while serializing.

Duplicate keys

object_pairs_hook=unique

Can reject repeated names at each object level.

JSON constants

parse_constant=reject

Can reject NaN and Infinity tokens.

Contract

type(value) is int

Excludes bool when an exact integer is required.

CSV read

csv.reader(stream, strict=True)

Parses a specified dialect; returns string cells.

CSV write

csv.writer(stream).writerows(rows)

Quotes fields; not spreadsheet formula mitigation.

File newline

open(path, newline="", encoding="utf-8")

Leaves newline handling to csv for real files.

TSV

delimiter="\t"

Specifies tabs plus the remaining csv dialect rules.

XML build

ET.Element("note")

Creates a node; set text without markup interpolation.

XML serialize

ET.tostring(root, encoding="unicode")

Escapes text; does not preserve original byte formatting.

XML find

root.find("a:note", {"a":"urn:atlas"})

Matches namespace URI and local name.

XML safety

ET.fromstring(authored_text)

Only trusted toy inputs in this pack.

TOML read

toml.loads(text)

Installed Tomli returns typed table values.

Schema boundary

validate(parsed_value)

A separate application step; no schema engine included.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Data 01 - JSON round trip

Use a JSON serializer for quotes and escapes. Bytes require an encoding; this example uses UTF-8. Round trips preserve these JSON-compatible values, not every Python type.

Expected stdout:

Café 25 False
True

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import json
value = {"title": "Café", "minutes": 25, "done": False}
text = json.dumps(value, ensure_ascii=False, allow_nan=False)
encoded = text.encode("utf-8")
restored = json.loads(encoded.decode("utf-8"))
print(restored["title"], restored["minutes"], restored["done"])
print(restored == value)
Data 02 - Reject ambiguous JSON

Python json accepts duplicate names and nonstandard NaN by default. These hooks enforce a stricter local policy. Syntax validity still does not enforce a schema or prevent large/deep input resource costs.

Expected stdout:

rejected
rejected
rejected

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import json
def reject_constant(value):
    raise ValueError("nonstandard number")
def unique(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate key")
        result[key] = value
    return result
for text in ['{"x":1,"x":2}', '{"x":NaN}', '{"x":}']:
    try:
        json.loads(text, object_pairs_hook=unique,
                   parse_constant=reject_constant)
    except ValueError:
        print("rejected")
Data 03 - Read quoted CSV

CSV is a family of dialects, not a typed schema. Delimiter, quoting, headers, row width and encoding need agreement. A reader keeps numeric-looking cells as strings by default.

Expected stdout:

Read, then code 20
Say "hello" str

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import csv, io
text = 'title,minutes\r\n"Read, then code",20\r\n"Say ""hello""",5\r\n'
rows = list(csv.reader(io.StringIO(text, newline=""), strict=True))
print(rows[1][0], rows[1][1])
print(rows[2][0], type(rows[2][1]).__name__)
Data 04 - Write CSV safely

The writer handles embedded commas, quotes and newlines. When using real files pass encoding="utf-8" and newline="". CSV quoting does not neutralize spreadsheet formulas; these examples are parser exercises, not spreadsheet-safe exports.

Expected stdout:

True
Line "2"

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import csv, io
rows = [["title", "note"], ["Café", 'Line 1\nLine "2"']]
buffer = io.StringIO(newline="")
csv.writer(buffer, lineterminator="\r\n").writerows(rows)
text = buffer.getvalue()
restored = list(csv.reader(io.StringIO(text, newline="")))
print(restored == rows)
print(restored[1][1].splitlines()[1])
Data 05 - Choose a TSV dialect

TSV changes the delimiter, but quoting and newline conventions still need agreement. This toy uses Python csv default quote rules with a tab delimiter. Conversion to int is a separate application step.

Expected stdout:

Read Code
30

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import csv, io
text = "title\tminutes\nRead\t10\nCode\t20\n"
rows = list(csv.reader(io.StringIO(text, newline=""), delimiter="\t"))
if rows[0] != ["title", "minutes"] or any(len(r) != 2 for r in rows):
    raise ValueError("unexpected columns")
print(rows[1][0], rows[2][0])
print(sum(int(r[1]) for r in rows[1:]))
Data 06 - Build XML text

Construct a tree and serialize text to escape markup. Only tiny authored XML is parsed here. ElementTree is not a hardened parser for malicious data; no untrusted files, DTDs or external entities are accepted by this teaching workflow.

Expected stdout:

<note kind="study">A &amp; B &lt; C</note>
A & B < C

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import xml.etree.ElementTree as ET
root = ET.Element("note", {"kind": "study"})
root.text = 'A & B < C'
text = ET.tostring(root, encoding="unicode")
restored = ET.fromstring(text)
print(text)
print(restored.text)
Data 07 - XML namespaces and errors

Namespace identity is a URI, not a particular prefix. A parse error concerns well-formedness, not XSD validation. Explicit is not None avoids confusing an empty element with a missing one.

Expected stdout:

{urn:atlas}notes
Read
malformed XML

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import xml.etree.ElementTree as ET
text = '<notes xmlns="urn:atlas"><note>Read</note></notes>'
root = ET.fromstring(text)
item = root.find("a:note", {"a": "urn:atlas"})
print(root.tag)
print(item.text if item is not None else "missing")
try:
    ET.fromstring("<note></notes>")
except ET.ParseError:
    print("malformed XML")
Data 08 - Read TOML settings

Tested with installed Tomli 1.0.3, a private pip-vendored fallback on Python 3.9.6. The tomllib branch is for an already installed Python 3.11+ and was not executed here. No installation occurs. This covers a TOML 1.0 subset, not TOML 1.1.

Expected stdout:

Café
25 True

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

try:
    import tomllib as toml
except ImportError:
    from pip._vendor import tomli as toml

text = '[study]\ntitle = "Café"\nminutes = 25\nactive = true\n'
value = toml.loads(text)
print(value["study"]["title"])
print(value["study"]["minutes"], value["study"]["active"])
Data 09 - Reject invalid TOML

Duplicate keys, uppercase True and unterminated strings violate these TOML rules. Syntactically valid settings still need an application contract.

Expected stdout:

invalid TOML
invalid TOML
invalid TOML

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

try:
    import tomllib as toml
except ImportError:
    from pip._vendor import tomli as toml

for text in ['minutes = 1\nminutes = 2', 'active = True', 'title = "open']:
    try:
        toml.loads(text)
    except toml.TOMLDecodeError:
        print("invalid TOML")
Data exercise A - Validate JSON minutes

Try it first: Accept exactly the minutes key and an integer from 0 to 120. Reject booleans, extra keys and UTF-8 input longer than 256 bytes. State the duplicate-key policy.

A small application contract requires exactly one key and an integer in range; bool is intentionally rejected even though it subclasses int in Python. This version uses default duplicate-key handling; combine example 02 hooks if duplicate rejection is required. A size cap alone is not comprehensive hostile-input protection.

Expected stdout:

20
invalid
invalid

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import json

def load_minutes(text):
    if len(text.encode("utf-8")) > 256:
        raise ValueError("too large")
    value = json.loads(text)
    if not isinstance(value, dict) or set(value) != {"minutes"}:
        raise ValueError("keys")
    n = value["minutes"]
    if type(n) is not int or not 0 <= n <= 120:
        raise ValueError("minutes")
    return n

for text in ['{"minutes":20}', '{"minutes":true}', '{"minutes":121}']:
    try:
        print(load_minutes(text))
    except ValueError:
        print("invalid")
Data exercise B - Convert CSV records

Try it first: Read a fixed two-column CSV dialect, validate up to ten records, and sum minutes. Reject negative values, extra columns and values over 120.

Row shape, header, nonblank labels and ASCII integer syntax are checked after parsing. This bounded toy totals at most ten records. csv.Error is a distinct possible syntax failure for malformed quoting.

Expected stdout:

30
invalid record

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import csv, io

def total(text):
    if len(text.encode("utf-8")) > 1024:
        raise ValueError("too large")
    rows = list(csv.reader(io.StringIO(text, newline=""), strict=True))
    if not rows or rows[0] != ["title", "minutes"] or len(rows) > 11:
        raise ValueError("header or row count")
    result = 0
    for row in rows[1:]:
        if len(row) != 2 or not row[0].strip() or not row[1].isascii() or not row[1].isdigit():
            raise ValueError("record")
        n = int(row[1])
        if n > 120:
            raise ValueError("range")
        result += n
    return result

print(total("title,minutes\nRead,10\nCode,20\n"))
try:
    total("title,minutes\nRead,-1\n")
except ValueError:
    print("invalid record")
Data exercise C - Check XML structure

Try it first: Require a note root with one nonblank title child, no attributes/nested elements, and no non-whitespace mixed text. Explain the trust boundary.

This application check is for tiny trusted authored strings only. It is not an XSD validator, a byte-preserving round trip or a safe untrusted XML entry point. Default ElementTree parsing can discard comments and processing instructions.

Expected stdout:

Read
invalid title

Test record: passed; CPython 3.9.6; stdlib json/csv/ElementTree; Tomli 1.0.3 where applicable; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

import xml.etree.ElementTree as ET

def title(text):
    root = ET.fromstring(text)
    children = list(root)
    if root.tag != "note" or root.attrib or len(children) != 1:
        raise ValueError("note structure")
    child = children[0]
    if child.tag != "title" or child.attrib or len(child):
        raise ValueError("title structure")
    if (root.text or "").strip() or (child.tail or "").strip():
        raise ValueError("mixed content")
    value = (child.text or "").strip()
    if not value:
        raise ValueError("empty title")
    return value

print(title("<note><title> Read </title></note>"))
try:
    title("<note><title /></note>")
except ValueError:
    print("invalid title")
Tested learning pack

C Foundations

Core types, control flow, functions, arrays, strings, ownership and lifetimes, expected errors, separate build stages and tests. Introductory c17 subset only.

Learners who have practiced basic control flow and can invoke an installed compiler. Allow 5 to 7 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Export one entry source and any companion files to a fresh practice folder. Compile with clang -std=c17 -Wall -Wextra -Wpedantic -Werror "C 01 Values.c" -o "Atlas example", then run ./"Atlas example" only after compilation succeeds. The C two-file example also needs "Atlas math.c" on the command line. These are recorded installed tools; do not run a package manager. The browser exports source only and never invokes the compiler. Use separate fresh directories to avoid executing stale output. Exact test environment: Apple Clang 21.0.0 (clang-2100.3.34.2); arm64 macOS 27.0.1.

Configuration: Build instructions.txt
Export one entry source and any companion files to a fresh practice folder. Compile with clang -std=c17 -Wall -Wextra -Wpedantic -Werror "C 01 Values.c" -o "Atlas example", then run ./"Atlas example" only after compilation succeeds. The C two-file example also needs "Atlas math.c" on the command line. These are recorded installed tools; do not run a package manager. The browser exports source only and never invokes the compiler. Use separate fresh directories to avoid executing stale output.

1. Choose C17 deliberately

C and C++ are separate languages. Compile .c files with clang -std=c17; this pack uses a hosted subset, not every C17 facility. Apple Clang 21.0.0 is the tested implementation. Integer widths, plain-char signedness, object layout and diagnostics vary; the examples avoid relying on a specific int width.

2. Build stages are distinct

Preprocessing includes headers, compilation checks and translates each translation unit, and linking resolves definitions. A declaration in a header is not a separately linked definition. A successful build does not demonstrate expected output. The harness checks syntax, creates objects, links and executes in fresh directories.

3. Values and control flow

Initialize objects before reading them, use matching printf format specifiers and keep conditions explicit. Signed integer overflow is undefined behavior. Tiny fixed values make simple examples tractable; the checked-addition exercise checks limits before adding.

4. Functions carry contracts

An int pointer alone does not communicate a valid length or lifetime. A function taking a pointer and count depends on the caller providing actual live elements. Use return status plus an output value for expected failures, and avoid using an output value unless the call succeeded.

5. Arrays and strings need bounds

Arrays hold a fixed number of elements. Most array expressions convert to pointers, so a pointer parameter loses the array bound. C strings require a zero terminator. Bound formatting, check truncation, and do not use unchecked strcpy, gets or unbounded input recipes. Byte lengths are not Unicode text lengths.

6. Storage duration and ownership

Automatic objects live for their scope; string literals have static storage duration. Allocated storage lasts until it is freed. Establish one responsible owner, check allocation, release once and stop using all aliases afterward. Returning a pointer to a local object or reading freed storage is not a valid teaching pattern.

7. Errors and tests

Check conversion status, end pointers and range policy. Expected invalid data is different from undefined behavior. assert provides test checks only while NDEBUG is undefined; input validation needs ordinary control flow. Deliberately invalid source fixtures are compiler rejection tests and are never executed.

8. Practice within limits

All inputs are authored, tiny and local. The harness also runs accepted examples with installed AddressSanitizer and UndefinedBehaviorSanitizer when verified available. These can detect some faults on executed paths; they do not prove safety or general correctness. No file I/O, arbitrary pointers, networking, concurrency, production integration or allocation-failure injection is included.

Quick reference

Entry

int main(void)

Hosted C entry point returns a process status.

Boolean

#include <stdbool.h>

C17 bool, true and false macros.

Output

printf("%d", value)

Format must match promoted argument type.

Length

size_t / %zu

Unsigned size type and matching printf conversion.

Branch

if (condition) { ... }

An explicit conditional block.

Loop

for (size_t i = 0; i < count; ++i)

Index only valid elements.

Function

bool operation(int input, int *out)

Separate success from result.

Read-only access

const int *values

Does not grant ownership or validate lifetime.

Array length

sizeof a / sizeof a[0]

Only at an actual array, not a pointer parameter.

Formatting

snprintf(buffer, capacity, ...)

Check negative return and required size.

String length

strlen(terminated_string)

Requires a valid terminator; counts bytes.

Allocation

calloc(count, sizeof *pointer)

Check failure; bound count and lifetime.

Release

free(pointer)

Release owned allocated storage once.

Conversion

strtol(text, &end, 10)

Check no-conversion, trailing content and ERANGE.

Test

assert(condition)

Can disappear when NDEBUG is defined.

Stages

-fsyntax-only / -c / link / run

Different checks with different failure modes.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

C 01 - Types and output

C17 uses stdbool.h for bool. Format specifiers must match argument types. Division by a floating operand produces a floating result; the display rounds to two decimal places.

Expected stdout:

Minutes: 25
Hours: 0.42
Ready: yes

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <stdbool.h>
#include <stdio.h>
int main(void) {
    const int minutes = 25;
    const double hours = minutes / 60.0;
    const bool ready = minutes > 0;
    printf("Minutes: %d\nHours: %.2f\nReady: %s\n",
           minutes, hours, ready ? "yes" : "no");
    return 0;
}
C 02 - Branches and loops

The loop is bounded and the small integer sum cannot overflow. Braces make the scope of each branch explicit. Do not generalize the arithmetic bound to arbitrary input.

Expected stdout:

Even total: 6

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <stdio.h>
int main(void) {
    int total = 0;
    for (int n = 1; n <= 4; ++n) {
        if (n % 2 == 0) { total += n; }
    }
    printf("Even total: %d\n", total);
    return 0;
}
C 03 - A checked function

Return status separately from an output value. A non-null output pointer must also point to a live writable int; a null check alone cannot validate pointer lifetime or ownership.

Expected stdout:

Double: 40
Invalid rejected: yes

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <stdbool.h>
#include <stdio.h>
static bool valid_minutes(int n) { return n >= 0 && n <= 120; }
static bool double_minutes(int n, int *out) {
    if (out == NULL || !valid_minutes(n)) { return false; }
    *out = n * 2;
    return true;
}
int main(void) {
    int result = 0;
    if (!double_minutes(20, &result)) { return 1; }
    printf("Double: %d\n", result);
    printf("Invalid rejected: %s\n",
           !double_minutes(-1, &result) ? "yes" : "no");
    return 0;
}
C 04 - Arrays and lengths

The count expression works where values is an array, not after it becomes a pointer parameter. For a nonzero count the caller must supply that many live elements, and every intermediate sum as well as the final sum must fit int. The empty case never dereferences NULL.

Expected stdout:

Count: 3
Total: 60
Empty: 0

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <stddef.h>
#include <stdio.h>
static int total(const int *values, size_t count) {
    int result = 0;
    for (size_t i = 0; i < count; ++i) { result += values[i]; }
    return result;
}
int main(void) {
    const int values[] = {10, 20, 30};
    const size_t count = sizeof values / sizeof values[0];
    printf("Count: %zu\nTotal: %d\n", count, total(values, count));
    printf("Empty: %d\n", total(NULL, 0));
    return 0;
}
C 05 - Bounded string formatting

A C string needs a terminating zero byte. snprintf reports the number of characters that would have been written, excluding the terminator. Check negative returns before conversion. strlen counts bytes here, not user-perceived Unicode characters.

Expected stdout:

Read:20 (7 bytes)
Truncation detected: yes

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <stdio.h>
#include <string.h>
int main(void) {
    char label[16];
    int n = snprintf(label, sizeof label, "%s:%d", "Read", 20);
    if (n < 0 || (size_t)n >= sizeof label) { return 1; }
    printf("%s (%zu bytes)\n", label, strlen(label));
    char tiny[4];
    n = snprintf(tiny, sizeof tiny, "%s", "abcdef");
    if (n < 0) { return 1; }
    printf("Truncation detected: %s\n",
           (size_t)n >= sizeof tiny ? "yes" : "no");
    return 0;
}
C 06 - Structs and explicit state

Struct assignment copies member values. The title pointer is copied, not the pointed-to text. Both point to the same string literal with static lifetime; neither code path writes through it.

Expected stdout:

Read: 20
Original open: yes; copy done: yes

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <stdio.h>
enum State { OPEN, DONE };
struct Task { const char *title; int minutes; enum State state; };
int main(void) {
    struct Task task = {"Read", 20, OPEN};
    struct Task copy = task;
    copy.state = DONE;
    printf("%s: %d\n", task.title, task.minutes);
    printf("Original open: %s; copy done: %s\n",
           task.state == OPEN ? "yes" : "no",
           copy.state == DONE ? "yes" : "no");
    return 0;
}
C 07 - One allocation and one owner

This function owns one small allocation, checks failure, uses it only during its lifetime, then frees it once. Assigning NULL only changes this pointer; it would not repair dangling aliases. Prefer fixed arrays when dynamic storage is unnecessary. Allocation failure is handled but not fault-injected by this pack.

Expected stdout:

Values: 1 2 3
Owner released storage

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    const size_t count = 3;
    int *values = calloc(count, sizeof *values);
    if (values == NULL) { fputs("Allocation failed\n", stderr); return 1; }
    for (size_t i = 0; i < count; ++i) { values[i] = (int)i + 1; }
    printf("Values: %d %d %d\n", values[0], values[1], values[2]);
    free(values);
    values = NULL;
    puts("Owner released storage");
    return 0;
}
C 08 - Parse and report errors

For these valid zero-terminated strings, strtol supplies an end pointer and range status. This policy accepts leading whitespace and a sign if the final value is in range; it rejects trailing content. The output is only assigned after success.

Expected stdout:

20
invalid
invalid
invalid

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static bool parse_minutes(const char *s, int *out) {
    if (s == NULL || out == NULL) { return false; }
    char *end = NULL;
    errno = 0;
    long value = strtol(s, &end, 10);
    if (s == end || *end != '\0' || errno == ERANGE ||
        value < 0 || value > 120) { return false; }
    *out = (int)value;
    return true;
}
int main(void) {
    const char *inputs[] = {"20", "x", "121", "15tail"};
    for (size_t i = 0; i < 4; ++i) {
        int value = 0;
        if (parse_minutes(inputs[i], &value)) { printf("%d\n", value); }
        else { puts("invalid"); }
    }
    return 0;
}
C 09 - Compile and link two files

The header declares the contract; a separate .c file defines it. Compile both source files and link their objects, or pass both .c files to one compiler invocation. The function contract is a value from 0 to 120.

Expected stdout:

Double: 12

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <stdio.h>
#include "Atlas math.h"
int main(void) {
    printf("Double: %d\n", atlas_double(6));
    return 0;
}

Companion: Atlas math.h

#ifndef ATLAS_MATH_H
#define ATLAS_MATH_H
int atlas_double(int value); /* caller supplies 0..120 */
#endif

Companion: Atlas math.c

#include "Atlas math.h"
int atlas_double(int value) { return value * 2; }
C exercise A - An empty average

Try it first: Return an explicit success status for an average. Reject an empty input, more than ten entries or out-of-range minutes without dividing by zero.

At most ten values in 0..120 keeps the sum bounded. The caller still owns the array and must supply n actual live elements. Failure leaves the output unchanged.

Expected stdout:

Average: 15.0
empty rejected

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
static bool average(const int *xs, size_t n, double *out) {
    if (xs == NULL || out == NULL || n == 0 || n > 10) { return false; }
    int sum = 0;
    for (size_t i = 0; i < n; ++i) {
        if (xs[i] < 0 || xs[i] > 120) { return false; }
        sum += xs[i];
    }
    *out = (double)sum / (double)n;
    return true;
}
int main(void) {
    const int xs[] = {10, 20}; double result = 0;
    if (!average(xs, 2, &result)) { return 1; }
    printf("Average: %.1f\n", result);
    puts(!average(NULL, 0, &result) ? "empty rejected" : "unexpected");
    return 0;
}
C exercise B - Checked addition

Try it first: Add two ints only when their mathematical sum fits int. Demonstrate both boundary rejections without actually overflowing.

Check limits before performing signed addition. Signed overflow is undefined behavior; checking the result afterward is too late. The subtraction guards are themselves valid for their sign branches.

Expected stdout:

Sum: 30
upper rejected
lower rejected

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
static bool add(int a, int b, int *out) {
    if (out == NULL || (b > 0 && a > INT_MAX - b) ||
        (b < 0 && a < INT_MIN - b)) { return false; }
    *out = a + b;
    return true;
}
int main(void) {
    int result = 0;
    if (!add(10, 20, &result)) { return 1; }
    printf("Sum: %d\n", result);
    puts(!add(INT_MAX, 1, &result) ? "upper rejected" : "unexpected");
    puts(!add(INT_MIN, -1, &result) ? "lower rejected" : "unexpected");
    return 0;
}
C exercise C - Runtime assertions

Try it first: Write four boundary assertions for inclusive 0..120. Explain why a successful compilation does not prove these assertions were executed.

These four runtime assertions run with NDEBUG undefined in the test build. assert can be compiled out and is not a substitute for validating external input in released software.

Expected stdout:

Assertions: 4 passed

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c17 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
static bool valid_minutes(int n) { return n >= 0 && n <= 120; }
int main(void) {
    assert(valid_minutes(0));
    assert(valid_minutes(120));
    assert(!valid_minutes(-1));
    assert(!valid_minutes(121));
    puts("Assertions: 4 passed");
    return 0;
}

Expected compiler rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: C 01 - Types and output

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: const-qualified.

int main(void) { const int n = 1; n = 2; return n; }
Expected rejection: C 03 - A checked function

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: too few arguments.

static int twice(int n) { return n * 2; }
int main(void) { return twice(); }
Expected rejection: C 09 - Compile and link two files

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: format specifies type.

#include <stdio.h>
int main(void) { printf("%d\n", "text"); return 0; }
Expected rejection: C exercise C - Runtime assertions

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: static assertion failed.

_Static_assert(sizeof(char) == 2, "deliberate failure");
int main(void) { return 0; }
Tested learning pack

C++ Foundations

Core types, control flow, functions, arrays, strings, ownership and lifetimes, expected errors, separate build stages and tests. Introductory c++20 subset only.

Learners who have practiced basic control flow and can invoke an installed compiler. Allow 5 to 7 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Export one entry source and any companion files to a fresh practice folder. Compile with clang++ -std=c++20 -Wall -Wextra -Wpedantic -Werror "C++ 01 Values.cpp" -o "Atlas example", then run ./"Atlas example" only after compilation succeeds. These are recorded installed tools; do not run a package manager. The browser exports source only and never invokes the compiler. Use separate fresh directories to avoid executing stale output. Exact test environment: Apple Clang 21.0.0 (clang-2100.3.34.2); arm64 macOS 27.0.1; libc++ 220106.

Configuration: Build instructions.txt
Export one entry source and any companion files to a fresh practice folder. Compile with clang++ -std=c++20 -Wall -Wextra -Wpedantic -Werror "C++ 01 Values.cpp" -o "Atlas example", then run ./"Atlas example" only after compilation succeeds. These are recorded installed tools; do not run a package manager. The browser exports source only and never invokes the compiler. Use separate fresh directories to avoid executing stale output.

1. Choose C++20 deliberately

Compile .cpp files with clang++ -std=c++20 so the driver links the C++ library. The installed Apple Clang 21.0.0 and libc++ 220106 support the subset actually tested here. Enabling a standard mode does not prove every feature is implemented; modules, ranges pipelines, coroutines and platform-specific APIs are outside this pack.

2. Prefer owning values

Use std::string, std::array and std::vector to express ownership. Copying a value container copies its values rather than simply sharing a C pointer. A vector can reallocate and invalidate pointers or views; the examples do not retain such views across mutation.

3. References and views borrow

A reference, string_view or span does not own the referred object and does not extend its lifetime. Keep the owner alive and storage stable for all uses. span carries a bound but C++20 operator[] is not a bounds-checked operation; range iteration or a deliberately checked access is often clearer.

4. Functions express results

An optional result represents expected absence without inventing a sentinel or exposing an output pointer. Check engagement before dereferencing. const restricts mutation through the given access path; it is not a general ownership or thread-safety guarantee.

5. RAII and unique ownership

Resource Acquisition Is Initialization associates a resource with an object lifetime. Containers and unique_ptr release owned storage automatically at normal destruction. std::move enables move operations; it does not itself transfer or destroy anything. This unique_ptr move empties its source, while other moved-from types have different contracts.

6. Errors remain observable

Use an optional for expected missing results, error codes where an API defines them, and exceptions where appropriate. Catch the expected exception by reference. vector::at throws on an invalid index; accessing an unchecked invalid index would be undefined behavior and is never demonstrated here.

7. Build and test separately

Header definitions, object compilation and linking have distinct roles. constexpr permits compile-time evaluation when its conditions are met; static_assert demands a compile-time truth. Runtime assert and stdout checks are separate evidence. Negative compiler fixtures are intentionally invalid and are not counted as successfully executing programs.

8. Practice within limits

The examples avoid raw owning new/delete, unchecked C string operations and arbitrary external input. Lifetime rules still matter in C++. Sanitizer success is limited to the executed paths and cannot certify safety. No deployment, concurrency, ABI compatibility, allocation-failure injection or full standard conformance is claimed.

Quick reference

Initialization

int count{3}

Braces reject many narrowing conversions.

Owning text

std::string

Owns character storage with value semantics.

Fixed array

std::array<T, N>

Owns a fixed number of elements.

Dynamic sequence

std::vector<T>

Owns elements; mutation may invalidate views.

Borrowed range

std::span<const T>

C++20 view, with length but no ownership.

Borrowed text

std::string_view

Does not extend owner lifetime or require a terminator.

Optional

std::optional<T> / std::nullopt

A result value or explicit absence.

Unique owner

std::make_unique<T>(...)

Creates storage managed by unique_ptr.

Move

std::move(value)

Enables move selection; follow type-specific postconditions.

Checked access

values.at(index)

Throws out_of_range if invalid.

Exception

catch (const std::out_of_range&)

Handle the expected failure type.

Parsing

std::from_chars(first, last, value)

Integer conversion reports end pointer and error code.

Compile-time test

static_assert(expression)

Must be a constant expression evaluating true.

Runtime test

assert(expression)

Executes only when enabled; not input validation.

Cleanup

~Type()

Destructor runs at normal object destruction.

Driver

clang++ -std=c++20

Pins language mode and links the C++ library.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

C++ 01 - Values and initialization

std::string owns its character storage. Braced initialization rejects many narrowing conversions. Stream output does not use C printf format strings.

Expected stdout:

Read: 25
true

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <iostream>
#include <string>
int main() {
    const std::string title{"Read"};
    const int minutes{25};
    const bool ready{minutes > 0};
    std::cout << title << ": " << minutes << '\n';
    std::cout << std::boolalpha << ready << '\n';
    return 0;
}
C++ 02 - Iterate over a value collection

Range iteration avoids manually maintaining an index for this operation. The fixed small values keep integer arithmetic in range; containers do not make signed overflow defined.

Expected stdout:

Even total: 6

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <array>
#include <iostream>
int main() {
    const std::array<int, 4> values{1, 2, 3, 4};
    int total{0};
    for (const int value : values) {
        if (value % 2 == 0) { total += value; }
    }
    std::cout << "Even total: " << total << '\n';
    return 0;
}
C++ 03 - Return an optional result

optional represents a value or absence without an output pointer. Check that a value exists before dereferencing. This C++20 example does not use later optional monadic or range APIs.

Expected stdout:

Double: 40
Invalid rejected: true

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <iostream>
#include <optional>
std::optional<int> double_minutes(int value) {
    if (value < 0 || value > 120) { return std::nullopt; }
    return value * 2;
}
int main() {
    const auto good = double_minutes(20);
    if (good) { std::cout << "Double: " << *good << '\n'; }
    std::cout << "Invalid rejected: " << std::boolalpha
              << !double_minutes(-1).has_value() << '\n';
    return 0;
}
C++ 04 - Owning arrays and borrowed spans

std::array owns its elements; C++20 std::span borrows a contiguous sequence and carries its length. A span does not extend lifetime and C++20 operator[] does not promise bounds checking. This loop consumes the span while the owner is alive. Every intermediate sum and the final sum must fit int; this is the arithmetic precondition, independent of span bounds.

Expected stdout:

Total: 60
Empty: 0

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <array>
#include <iostream>
#include <span>
int total(std::span<const int> values) {
    int sum{0};
    for (const int value : values) { sum += value; }
    return sum;
}
int main() {
    const std::array<int, 3> values{10, 20, 30};
    std::cout << "Total: " << total(values) << '\n';
    std::cout << "Empty: " << total(std::span<const int>{}) << '\n';
    return 0;
}
C++ 05 - Strings and borrowed views

string_view borrows; string owns. The owner remains alive and unmodified for every use of view. A view need not be zero-terminated. Byte counts are not general Unicode character counts.

Expected stdout:

Read
Bytes: 7
Copy: Read:20

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <iostream>
#include <string>
#include <string_view>
int main() {
    const std::string label{"Read:20"};
    const std::string_view view{label};
    std::cout << view.substr(0, 4) << '\n';
    std::cout << "Bytes: " << label.size() << '\n';
    const std::string copy{view};
    std::cout << "Copy: " << copy << '\n';
    return 0;
}
C++ 06 - Value semantics

The std::string member has value semantics, so changing the copy does not change the original. Contrast C struct copying a pointer member: that copies the address rather than the referenced characters.

Expected stdout:

Read: 20
Code: 20

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <iostream>
#include <string>
struct Task { std::string title; int minutes; };
int main() {
    const Task original{"Read", 20};
    Task copy = original;
    copy.title = "Code";
    std::cout << original.title << ": " << original.minutes << '\n';
    std::cout << copy.title << ": " << copy.minutes << '\n';
    return 0;
}
C++ 07 - Transfer unique ownership

unique_ptr owns one allocation and releases it automatically at scope exit. Moving transfers ownership; the source unique_ptr becomes empty. Do not generalize that empty-state guarantee to every moved-from type. Allocation failure is not fault-injected.

Expected stdout:

First empty: true
Value: 42

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <iostream>
#include <memory>
#include <utility>
int main() {
    auto first = std::make_unique<int>(42);
    auto second = std::move(first);
    std::cout << "First empty: " << std::boolalpha << !first << '\n';
    std::cout << "Value: " << *second << '\n';
    return 0;
}
C++ 08 - Recover from an expected exception

vector::at checks the index and throws out_of_range. vector::operator[] does not provide that guarantee in the C++20 contract. Catch the expected type by reference; no out-of-bounds access is performed.

Expected stdout:

First: 10
Index rejected

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
    const std::vector<int> values{10, 20};
    std::cout << "First: " << values.at(0) << '\n';
    try {
        std::cout << values.at(9) << '\n';
    } catch (const std::out_of_range&) {
        std::cout << "Index rejected\n";
    }
    return 0;
}
C++ 09 - A header and compile-time contract

The inline constexpr definition is visible in the header. static_assert is checked during compilation; the printed output is separate runtime evidence. This is ordinary header inclusion, not C++20 modules.

Expected stdout:

Double: 12

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <iostream>
#include "Atlas math.hpp"
static_assert(atlas_double(6) == 12);
int main() {
    std::cout << "Double: " << atlas_double(6) << '\n';
    return 0;
}

Companion: Atlas math.hpp

#ifndef ATLAS_MATH_HPP
#define ATLAS_MATH_HPP
// Caller supplies 0..120.
inline constexpr int atlas_double(int value) { return value * 2; }
#endif
C++ exercise A - An optional average

Try it first: Return an optional average over at most ten values in 0..120. Demonstrate empty input without dereferencing an empty optional.

The span borrows valid storage, while optional owns a result value or represents absence. The function validates at most ten minute values and never divides by zero.

Expected stdout:

Average: 15
Empty rejected: true

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <array>
#include <iostream>
#include <optional>
#include <span>
std::optional<double> average(std::span<const int> values) {
    if (values.empty() || values.size() > 10) { return std::nullopt; }
    int sum{0};
    for (const int n : values) {
        if (n < 0 || n > 120) { return std::nullopt; }
        sum += n;
    }
    return static_cast<double>(sum) / static_cast<double>(values.size());
}
int main() {
    const std::array<int, 2> values{10, 20};
    const auto result = average(values);
    if (!result) { return 1; }
    std::cout << "Average: " << *result << '\n';
    std::cout << "Empty rejected: " << std::boolalpha
              << !average(std::span<const int>{}).has_value() << '\n';
    return 0;
}
C++ exercise B - Parse a complete number

Try it first: Parse the entire supplied view, reject errors and trailing content, and keep range policy separate from conversion.

Integer from_chars reports an error code and end pointer without throwing. Unlike strtol, this conversion does not skip leading whitespace or accept a leading plus sign. The policy requires complete consumption and values in 0..120.

Expected stdout:

20
invalid
invalid
invalid

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <charconv>
#include <initializer_list>
#include <iostream>
#include <optional>
#include <string_view>
#include <system_error>
std::optional<int> minutes(std::string_view text) {
    if (text.empty()) { return std::nullopt; }
    int value{0};
    const auto result = std::from_chars(text.data(), text.data() + text.size(), value);
    if (result.ec != std::errc{} || result.ptr != text.data() + text.size() ||
        value < 0 || value > 120) { return std::nullopt; }
    return value;
}
int main() {
    for (const auto text : {"20", "x", "121", "15tail"}) {
        const auto result = minutes(text);
        if (result) { std::cout << *result << '\n'; }
        else { std::cout << "invalid\n"; }
    }
    return 0;
}
C++ exercise C - Test a lifetime boundary

Try it first: Track one automatic object with a constructor and destructor. Assert the live count inside and after its scope; ensure the count outlives the object.

A destructor runs at this ordinary scope exit. The referenced count outlives the Counter, and copying is disabled to preserve this toy invariant. This does not demonstrate cleanup after forced termination, leaks, concurrency or every exceptional path.

Expected stdout:

Inside: 1
After scope: 0

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); c++20 normal and AddressSanitizer/UndefinedBehaviorSanitizer builds; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

#include <cassert>
#include <iostream>
struct Counter {
    int& live;
    explicit Counter(int& count) : live(count) { ++live; }
    ~Counter() { --live; }
    Counter(const Counter&) = delete;
    Counter& operator=(const Counter&) = delete;
};
int main() {
    int live{0};
    {
        Counter owner{live};
        assert(live == 1);
        std::cout << "Inside: " << live << '\n';
    }
    assert(live == 0);
    std::cout << "After scope: " << live << '\n';
    return 0;
}

Expected compiler rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: C++ 01 - Values and initialization

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: cannot be narrowed.

int main() { int n{1.5}; return n; }
Expected rejection: C++ 07 - Transfer unique ownership

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: implicitly-deleted copy constructor.

#include <memory>
int main() { auto a = std::make_unique<int>(1); auto b = a; }
Expected rejection: C++ 09 - A header and compile-time contract

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: static assertion failed.

static_assert(2 + 2 == 5, "deliberate failure");
int main() {}
Expected rejection: C++ exercise C - Test a lifetime boundary

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: const-qualified.

int main() { const int n = 1; n = 2; return n; }
Tested learning pack

Ruby Foundations

Core values, control flow, functions, collections, text, regular expressions, temporary files, expected errors, JSON, local modules and tests. No external data, packages or deployment.

Learners comfortable saving a source file and running an installed interpreter. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Ruby 2.6.10p210 is installed and end-of-life upstream. Run /usr/bin/ruby followed by the quoted entry filename in a new practice folder. Save companions beside the entry file. Core libraries only; no package manager is used. The browser exports text and never executes it. Syntax checks are distinct from runtime tests and are not arbitrary-code sandboxes.

Configuration: Run instructions.txt
Ruby 2.6.10p210 is installed and end-of-life upstream. Run /usr/bin/ruby followed by the quoted entry filename in a new practice folder. Save companions beside the entry file. Core libraries only; no package manager is used. The browser exports text and never executes it. Syntax checks are distinct from runtime tests and are not arbitrary-code sandboxes.

1. Pin the installed interpreter

Ruby 2.6.10 is an end-of-life branch. This pack records offline teaching behavior on this Mac, not a deployment recommendation. Ruby 3 differences and installed gems are outside its scope. Run a saved .rb with /usr/bin/ruby; the browser only exports text.

2. Objects, truth and conversion

Ruby variables refer to objects. Only false and nil are false-valued: 0 and empty strings are true-valued. Integer division floors toward negative infinity; fdiv produces floating-point division. Validate the intended input policy before converting text; to_i is not strict whole-input validation.

3. Methods and blocks

Methods return their last expression unless return is explicit. each yields values to a block, and select builds a filtered array. Keep calculations separate from output and catch only expected exceptions. The examples use ordinary Ruby 2.6 syntax, not later pattern-matching or endless-method syntax.

4. Collections and mutation

Arrays and hashes store object references. dup is shallow; copying the outer array does not duplicate its nested rows. Our row-copy exercise is deliberately limited to one known structure. Do not use a single mutable Hash default object as if it were independent per key.

5. Strings and regular expressions

Strings have an encoding. Character length and byte size differ, and character count is not grapheme count. Use Regexp.escape for literal pattern data and \A/\z for the entire string. These bounded authored patterns are not a general defense against hostile regex workloads.

6. Files have ownership

Only newly created temporary toy directories are writable in the file example. File.open uses an explicit UTF-8 mode and a block to close the handle. Kernel.open is avoided because pipe-prefixed input can invoke a process. No real-document path or network input is accepted.

7. Errors and JSON contracts

A rescue handles a selected exception, while nil can represent an absent result when documented. JSON.parse with create_additions: false produces data; it does not enforce an application schema or reject duplicate names by itself. No Marshal loading or arbitrary code evaluation is used.

8. Modules and tests

require_relative loads the supplied trusted companion. Code loading can execute code, so a practice folder must contain only files you control. Syntax acceptance is separate from actual program output and boundary tests. Four assertion cases demonstrate observable failure; the harness is not a sandbox for arbitrary submissions.

Quick reference

Values

Integer / Float / String / nil

Objects and absence; / differs for integer operands.

Truth

false / nil

Only these two are false-valued.

Flow

if / elsif / else / end

Choose a branch.

Blocks

each { |value| ... }

Visit each element; next skips an iteration.

Methods

def / return

Last expression is also an implicit return.

Arrays

[] / fetch / select

Ordered values; fetch can report missing indices.

Hashes

{} / fetch / keys.sort

Mappings with explicit lookup and report order.

Mutation

dup / map(&:dup)

Shallow copy only; nested objects can remain shared.

Strings

length / bytesize

Characters versus bytes, not grapheme count.

Patterns

\A / \z / Regexp.escape

Whole-string boundaries and escaped literal data.

Parsing

Integer(text, 10)

Explicit conversion; validate the intended policy.

Errors

raise / rescue ArgumentError

Signal and recover from a specific expected error.

Files

File.open(path, mode) { |f| ... }

Fixed toy path, explicit encoding, block closes handle.

Temporary

Dir.mktmpdir(prefix, ".") { ... }

Own and clean one newly created directory.

Modules

require_relative / module

Load trusted companion code and namespace methods.

JSON

JSON.generate / JSON.parse

Serialization and parsing are separate from contract checks.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Ruby 01 - Values and interpolation

Values are objects. Integer division and floating-point division differ; interpolation formats values without changing them. nil represents absence.

Expected stdout:

Ada: 25 minutes
Integer division: 12
Float division: 12.5
Integer, String, NilClass

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

name = "Ada"
minutes = 25
puts "#{name}: #{minutes} minutes"
puts "Integer division: #{minutes / 2}"
puts "Float division: #{minutes / 2.0}"
puts [minutes.class, name.class, nil.class].join(", ")
Ruby 02 - Blocks and truth values

Only false and nil are false-valued in Ruby. Zero and empty strings are true-valued. each yields values to a block; next skips the rest of that iteration.

Expected stdout:

Even total: 6
Zero is true-valued
Empty text is true-valued
Nil is false-valued

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

total = 0
[1, 2, 3, 4].each do |value|
  next if value.odd?
  total += value
end
puts "Even total: #{total}"
zero = 0
empty = ''
absent = nil
puts "Zero is #{zero ? 'true-valued' : 'false-valued'}"
puts "Empty text is #{empty ? 'true-valued' : 'false-valued'}"
puts "Nil is #{absent ? 'true-valued' : 'false-valued'}"
Ruby 03 - A method contract

The final expression is returned. Validate before calculating; rescue only the expected ArgumentError. This contract accepts Integer values, not numeric text or floating point.

Expected stdout:

Double: 40
Text rejected

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

def double_minutes(value)
  raise ArgumentError, 'whole minutes 0..120 required' unless
    value.is_a?(Integer) && value.between?(0, 120)
  value * 2
end
puts "Double: #{double_minutes(20)}"
begin
  double_minutes('20')
rescue ArgumentError
  puts 'Text rejected'
end
Ruby 04 - Arrays and hash totals

An array is ordered; a hash maps keys to values. Sorting keys makes the report order deliberate. Hash.new(0) uses an immutable Integer default; do not generalize this pattern to one shared mutable default array.

Expected stdout:

code: 30
read: 30
Long sessions: 2

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

sessions = [['read', 20], ['code', 30], ['read', 10]]
totals = Hash.new(0)
sessions.each { |topic, minutes| totals[topic] += minutes }
totals.keys.sort.each { |topic| puts "#{topic}: #{totals.fetch(topic)}" }
puts "Long sessions: #{sessions.select { |_, n| n >= 20 }.length}"
Ruby 05 - Text, bytes and literal patterns

Source is UTF-8. String length counts characters, not grapheme clusters; bytesize counts encoded bytes. Escape a literal before placing it into a regular expression. The whole-string anchors are \A and \z; line anchors have different semantics.

Expected stdout:

Characters: 4; UTF-8 bytes: 5
Literal match: true
Different text: false
Digits only: false

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

label = "café"
puts "Characters: #{label.length}; UTF-8 bytes: #{label.bytesize}"
literal = 'a+b'
pattern = /\A#{Regexp.escape(literal)}\z/
puts "Literal match: #{pattern.match?('a+b')}"
puts "Different text: #{pattern.match?('aaab')}"
puts "Digits only: #{/\A[0-9]+\z/.match?("20\n")}"
Ruby 06 - A disposable UTF-8 file

The block owns a newly created toy directory under the current practice folder. File.open blocks close their handles; mktmpdir removes its own directory when its block finishes. File.open is intentional: Kernel.open can interpret pipe-prefixed strings as process commands. No external path is accepted.

Expected stdout:

Read: café
Toy directory removed: true

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

require 'tmpdir'
folder = nil
Dir.mktmpdir('atlas-ruby-', '.') do |dir|
  folder = dir
  path = File.join(dir, 'note.txt')
  File.open(path, 'w:UTF-8') { |file| file.write("café\n") }
  text = File.open(path, 'r:UTF-8') { |file| file.read }
  puts "Read: #{text.chomp}"
end
puts "Toy directory removed: #{!File.exist?(folder)}"
Ruby 07 - Parse a narrow input contract

This policy accepts decimal text 0..120 without signs, surrounding whitespace or leading zeroes. The regex bounds length before conversion. Checking nil preserves zero as a valid result. Integer alone accepts a broader syntax; to_i would silently parse some partial input. Malformed or non-ASCII-compatible string encoding is rejected before regular-expression matching.

Expected stdout:

20
0
invalid
invalid
invalid
invalid

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

def minutes(text)
  return nil unless text.is_a?(String) && text.valid_encoding? &&
    text.encoding.ascii_compatible? &&
    /\A(?:0|[1-9][0-9]{0,2})\z/.match?(text)
  number = Integer(text, 10)
  number <= 120 ? number : nil
end
['20', '0', '121', ' 20', '+20', '20x'].each do |text|
  value = minutes(text)
  puts(value.nil? ? 'invalid' : value)
end
Ruby 08 - A local module

Save the companion beside the entry file. require_relative resolves relative to this source file. A module provides a namespace; self.total defines a callable module method. The module has no demonstration output when loaded.

Expected stdout:

Total: 50

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

require_relative 'Atlas minutes'
puts "Total: #{AtlasMinutes.total([20, 30])}"

Companion: Atlas minutes.rb

module AtlasMinutes
  def self.total(values)
    raise ArgumentError, 'at most ten whole minutes 0..120' unless
      values.is_a?(Array) && values.length <= 10 &&
      values.all? { |n| n.is_a?(Integer) && n.between?(0, 120) }
    values.inject(0, :+)
  end
end
Ruby 09 - JSON is data

Generate escaping with the JSON library, then validate the decoded shape separately. This tiny authored input uses create_additions: false; never substitute JSON.load or Marshal.load for untrusted data. Default duplicate-name handling is not a duplicate-rejection policy. No general hostile-input or schema claim is made.

Expected stdout:

read: 20
Malformed JSON rejected

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

require 'json'
encoded = JSON.generate({'topic' => 'read', 'minutes' => 20})
data = JSON.parse(encoded, create_additions: false, max_nesting: 10)
valid = data.is_a?(Hash) && data.keys.sort == ['minutes', 'topic'] &&
  data['topic'].is_a?(String) && data['minutes'].is_a?(Integer) &&
  data['minutes'].between?(0, 120)
raise ArgumentError, 'wrong contract' unless valid
puts "#{data.fetch('topic')}: #{data.fetch('minutes')}"
begin
  JSON.parse('{', create_additions: false)
rescue JSON::ParserError
  puts 'Malformed JSON rejected'
end
Ruby exercise A - An optional average

Try it first: Implement an average of at most ten Integer minutes in 0..120. Return nil for empty input and reject invalid elements.

Validate the collection, return nil for absence, and divide as floating point only for a nonempty collection. This is a bounded teaching contract, not a general statistics library.

Expected stdout:

Average: 15.0
Empty: true

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

def average(values)
  raise ArgumentError, 'at most ten whole minutes 0..120' unless
    values.is_a?(Array) && values.length <= 10 &&
    values.all? { |n| n.is_a?(Integer) && n.between?(0, 120) }
  return nil if values.empty?
  values.inject(0, :+).fdiv(values.length)
end
puts "Average: #{average([10, 20])}"
puts "Empty: #{average([]).nil?}"
Ruby exercise B - Shallow copies

Try it first: Predict which mutation affects the original. Then copy each row and replace a numeric cell without changing the original.

dup copies one container level. map(&:dup) copies each row for this specific two-level structure, but the contained string is still shared. It is not a recursive deep copy.

Expected stdout:

After shallow edit: 30
After row edit: 30
Separate row: 40

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

original = [['read', 20]]
shallow = original.dup
shallow[0][1] = 30
puts "After shallow edit: #{original[0][1]}"
separate_rows = original.map(&:dup)
separate_rows[0][1] = 40
puts "After row edit: #{original[0][1]}"
puts "Separate row: #{separate_rows[0][1]}"
Ruby exercise C - Observable assertions

Try it first: Write checks for zero, normal input, the upper bound and a rejected negative value. Make an unexpected result exit unsuccessfully.

This small authored test uses raise to fail visibly. It executes three valid cases and one expected error check. A syntax check alone would not run these assertions.

Expected stdout:

Assertions: 4 passed

Test record: passed; Ruby 2.6.10p210; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

def double_minutes(value)
  raise ArgumentError unless value.is_a?(Integer) && value.between?(0, 120)
  value * 2
end
checks = 0
[[0, 0], [20, 40], [120, 240]].each do |input, expected|
  raise 'wrong result' unless double_minutes(input) == expected
  checks += 1
end
rejected = false
begin
  double_minutes(-1)
rescue ArgumentError
  rejected = true
end
raise 'expected rejection' unless rejected
checks += 1
puts "Assertions: #{checks} passed"

Expected syntax rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: Ruby 01 - Values and interpolation

Deliberately invalid source, never executed. Observed diagnostic category on the stated interpreter syntax checker: syntax error.

def unfinished(
Expected rejection: Ruby 02 - Blocks and truth values

Deliberately invalid source, never executed. Observed diagnostic category on the stated interpreter syntax checker: self.

self = 1
Expected rejection: Ruby 03 - A method contract

Deliberately invalid source, never executed. Observed diagnostic category on the stated interpreter syntax checker: dynamic constant assignment.

def value
  AtlasConstant = 1
end
Expected rejection: Ruby 04 - Arrays and hash totals

Deliberately invalid source, never executed. Observed diagnostic category on the stated interpreter syntax checker: formal argument cannot be a constant.

def value(AtlasConstant)
end
Tested learning pack

Perl Foundations

Core values, control flow, functions, collections, text, regular expressions, temporary files, expected errors, JSON, local modules and tests. No external data, packages or deployment.

Learners comfortable saving a source file and running an installed interpreter. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Perl 5.34.1 is installed; no other Perl version or platform was tested. Run /usr/bin/perl followed by the quoted entry filename in a new practice folder. Save companions beside the entry file. Core libraries only; no package manager is used. The browser exports text and never executes it. Syntax checks are distinct from runtime tests and are not arbitrary-code sandboxes.

Configuration: Run instructions.txt
Perl 5.34.1 is installed; no other Perl version or platform was tested. Run /usr/bin/perl followed by the quoted entry filename in a new practice folder. Save companions beside the entry file. Core libraries only; no package manager is used. The browser exports text and never executes it. Syntax checks are distinct from runtime tests and are not arbitrary-code sandboxes.

1. Pin the installed interpreter

This pack uses Perl 5.34.1 on macOS arm64 and already installed core modules. It uses Perl 5 lexical variables and ordinary subroutines, not Raku or later experimental features. Run /usr/bin/perl followed by the quoted .pl filename. No CPAN or package installation is needed.

2. Context affects values

Scalar and list context are central to Perl. An array in scalar context yields its count. Use eq for textual equality and == for numeric equality. Scalars can be interpreted as text or numbers, so this pack validates a decimal representation rather than claiming a strict historical type distinction.

3. Truth and absence

The string "0" is false in ordinary boolean context. Use defined when zero is a valid result. Defined-or // provides a fallback only for undef, unlike ||. Add strict and warnings to expose common mistakes; neither is a sandbox or complete input validator.

4. Functions and bounded control

Subroutines receive arguments in @_. Copy the values into lexical variables to avoid accidental alias writes. A for loop and next make filtering explicit; ensure while conditions progress. Range and count limits keep every exercise small and deterministic.

5. References and data structures

Array and hash references represent nested collections. An outer copy still shares nested references. The row-copy exercise duplicates exactly one known depth. Sort hash keys for deterministic reports; do not rely on hash iteration order.

6. Text, regex and encoding

use utf8 describes the source text, not an I/O handle. File encoding is explicit with :encoding(UTF-8). Quote literal regex content with \Q...\E and anchor whole strings with \A/\z. No dynamic regex code, shell interpolation or string eval is used.

7. Files, modules and errors

Use three-argument open, lexical handles, checked I/O results and newly created File::Temp directories. Cleanup is verified after normal process exit, not guaranteed after a crash. A module is executable trusted code; use lib adds only the companion directory. eval BLOCK catches expected exceptions; preserve $@ before another operation can change it.

8. Testing is runtime evidence

perl -c checks syntax but may execute BEGIN/CHECK blocks and use statements. It is not a safe way to inspect arbitrary code. Our invalid fixtures contain no custom compile-time blocks; the strict fixture loads only the trusted core strict pragma. Test::More executes four named runtime cases; JSON::PP parsing and custom shape checks do not establish JSON Schema validity.

Quick reference

Scope

use strict; use warnings; my

Lexical declarations and diagnostics.

Values

$scalar / @array / %hash

One value, ordered list, key/value mapping.

Context

scalar(@array)

Array length rather than its elements.

Comparison

eq / ==

Text equality versus numeric equality.

Truth

defined($value)

Preserve zero when testing for presence.

Flow

for / while / next

Bounded iteration and skipping.

Subroutines

sub / my ($value) = @_

Copy arguments into local variables.

References

[] / {} / -> / @$ref

Construct and access nested structures.

Defaults

//

Use fallback only when left side is undefined.

Patterns

\A / \z / \Q...\E

Whole-string boundaries and literal pattern quoting.

Encoding

use utf8 / :encoding(UTF-8)

Source encoding and file encoding are distinct.

Files

open my $fh, mode, path

Three-argument open separates mode and toy path.

Temporary

File::Temp::tempdir(..., CLEANUP => 1)

New directory; cleanup at normal exit.

Errors

eval { ...; 1 } / $@

Block exception handling; save error immediately.

Modules

package / use lib / use Module

Trusted code loading and namespacing.

Tests

Test::More is / ok

Executed assertions with named TAP output.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Perl 01 - Scalars and context

A scalar holds one value; an array holds a list. An array in scalar context yields its length. In ordinary boolean context undef, numeric zero, the empty string and the string "0" are false. This differs from Ruby. strict and warnings help expose mistakes; they are not security controls.

Expected stdout:

Ada: 3 sessions
List: 10, 20, 30
Zero text is false
Empty text is false

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
my $name = 'Ada';
my @minutes = (10, 20, 30);
my $count = @minutes;
print "$name: $count sessions\n";
print 'List: ', join(', ', @minutes), "\n";
print 'Zero text is ', ('0' ? 'true' : 'false'), "\n";
print 'Empty text is ', ('' ? 'true' : 'false'), "\n";
Perl 02 - Bounded control flow

Use braces around blocks, lexically scoped my variables, and a loop condition that progresses toward stopping. next skips the current iteration. These loops have fixed small bounds.

Expected stdout:

Even total: 6
Remaining: 0

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
my $total = 0;
for my $value (1 .. 4) {
    next if $value % 2;
    $total += $value;
}
print "Even total: $total\n";
my $remaining = 3;
while ($remaining > 0) { $remaining--; }
print "Remaining: $remaining\n";
Perl 03 - Subroutines and validation

Copy arguments from @_ into lexical variables. This contract validates a scalar decimal representation and accepts numeric 20 or text "20"; it does not distinguish their historical origin. eval BLOCK catches an exception; the final 1 marks success independently of a false result. It is not string eval.

Expected stdout:

Double: 40
Negative rejected

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
sub double_minutes {
    my ($value) = @_;
    die "invalid minutes\n" unless defined($value) && !ref($value) &&
        $value =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $value <= 120;
    return $value * 2;
}
print 'Double: ', double_minutes(20), "\n";
my $ok = eval { double_minutes(-1); 1 };
my $error = $@;
print "Negative rejected\n" if !$ok && $error eq "invalid minutes\n";
Perl 04 - Hashes and references

References permit nested structures. Dereference each array row explicitly. A hash does not promise report order, so sort keys. Defined-or // falls back for undef while preserving a defined zero.

Expected stdout:

code: 30
read: 30
Rows: 3

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
my @sessions = (['read', 20], ['code', 30], ['read', 10]);
my %totals;
for my $row (@sessions) {
    my ($topic, $minutes) = @$row;
    $totals{$topic} = ($totals{$topic} // 0) + $minutes;
}
for my $topic (sort keys %totals) { print "$topic: $totals{$topic}\n"; }
print 'Rows: ', scalar(@sessions), "\n";
Perl 05 - Literal regex and Unicode

use utf8 declares source encoding; it does not configure file handles. This decoded string length counts characters, not grapheme clusters. \Q...\E quotes literal pattern content; \A and \z anchor the entire string. No untrusted regex or executable regex code is accepted.

Expected stdout:

Characters: 4
Literal match: yes
Different text: no
Trailing newline: rejected

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
use utf8;
my $label = "café";
print 'Characters: ', length($label), "\n";
my $literal = 'a+b';
print 'Literal match: ', ('a+b' =~ /\A\Q$literal\E\z/ ? 'yes' : 'no'), "\n";
print 'Different text: ', ('aaab' =~ /\A\Q$literal\E\z/ ? 'yes' : 'no'), "\n";
print 'Trailing newline: ', ("20\n" =~ /\A[0-9]+\z/ ? 'accepted' : 'rejected'), "\n";
Perl 06 - A disposable UTF-8 file

A new File::Temp directory is created under the practice folder and removed at normal process exit. Three-argument open separates the fixed mode from the filename; lexical handles and checked close expose failures. UTF-8 layers apply at I/O. Cleanup after abrupt termination is not guaranteed; only authored toy paths are used.

Expected stdout:

Characters including newline: 5
Cleanup scheduled for normal process exit

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
use utf8;
use File::Temp qw(tempdir);
use File::Spec;
my $dir = tempdir('atlas-perl-XXXXXX', DIR => '.', CLEANUP => 1);
my $path = File::Spec->catfile($dir, 'note.txt');
open my $out, '>:encoding(UTF-8)', $path or die "open write: $!";
print {$out} "café\n" or die "write: $!";
close $out or die "close write: $!";
open my $in, '<:encoding(UTF-8)', $path or die "open read: $!";
my $text = do { local $/; <$in> };
close $in or die "close read: $!";
print 'Characters including newline: ', length($text), "\n";
print "Cleanup scheduled for normal process exit\n";
Perl 07 - Defined results and error recovery

Use defined when zero is a valid result. The explicit policy rejects signs, spaces, leading zeroes, references and values over 120. Numeric conversion alone can warn yet still produce a partial result; validate the full small representation first.

Expected stdout:

20
0
invalid
invalid
invalid
invalid

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
sub minutes {
    my ($text) = @_;
    return undef unless defined($text) && !ref($text) &&
        $text =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $text <= 120;
    return 0 + $text;
}
for my $text ('20', '0', '121', ' 20', '+20', '20x') {
    my $value = minutes($text);
    print defined($value) ? "$value\n" : "invalid\n";
}
Perl 08 - A local module

Save AtlasMinutes.pm beside the entry file. FindBin locates that directory; use lib adds this trusted practice directory. The package namespaces its routine and ends with a true value. Loading a Perl module executes code, so do not add an untrusted directory to the module path.

Expected stdout:

Total: 50

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
use FindBin qw($Bin);
use lib $Bin;
use AtlasMinutes;
print 'Total: ', AtlasMinutes::total([20, 30]), "\n";

Companion: AtlasMinutes.pm

package AtlasMinutes;
use strict;
use warnings;
sub total {
    my ($values) = @_;
    die "array required\n" unless ref($values) eq 'ARRAY' && @$values <= 10;
    my $total = 0;
    for my $value (@$values) {
        die "invalid minutes\n" unless defined($value) && !ref($value) &&
            $value =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $value <= 120;
        $total += $value;
    }
    return $total;
}
1;
Perl 09 - JSON and shape checks

JSON::PP is already installed. canonical makes object-key output deterministic. The contract checks scalar representations; it does not preserve or certify the JSON distinction between a number and numeric text. Duplicate-name rejection and general schema validation are not implemented. Use tiny authored data, never string eval.

Expected stdout:

read: 20
Malformed JSON rejected

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
use JSON::PP;
my $json = JSON::PP->new->canonical->max_depth(10);
my $encoded = $json->encode({topic => 'read', minutes => 20});
my $data = $json->decode($encoded);
die "wrong contract\n" unless ref($data) eq 'HASH' &&
    join(',', sort keys %$data) eq 'minutes,topic' &&
    !ref($data->{topic}) && defined($data->{topic}) &&
    !ref($data->{minutes}) && defined($data->{minutes}) &&
    $data->{minutes} =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $data->{minutes} <= 120;
print "$data->{topic}: $data->{minutes}\n";
my $ok = eval { $json->decode('{'); 1 };
print "Malformed JSON rejected\n" unless $ok;
Perl exercise A - An optional average

Try it first: Average at most ten minute values in 0..120. Reject invalid inputs and return undef for an empty array.

An array reference keeps the input as one argument. The bounded contract accepts integer decimal representations. Return undef for an empty collection and check defined before using the result.

Expected stdout:

Average: 15.0
Empty: absent

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
sub average {
    my ($values) = @_;
    die "array required\n" unless ref($values) eq 'ARRAY' && @$values <= 10;
    return undef unless @$values;
    my $total = 0;
    for my $n (@$values) {
        die "invalid minutes\n" unless defined($n) && !ref($n) &&
            $n =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $n <= 120;
        $total += $n;
    }
    return $total / @$values;
}
printf "Average: %.1f\n", average([10, 20]);
print 'Empty: ', (defined(average([])) ? 'value' : 'absent'), "\n";
Perl exercise B - Copy one level deliberately

Try it first: Predict aliasing, then duplicate each row so assigning a numeric cell no longer changes the original.

The first copy duplicates the outer array but shares row references. The second duplicates each row for this structure. Deeper references would still be shared; it is not a general recursive clone.

Expected stdout:

After shallow edit: 30
After row edit: 30
Separate row: 40

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
my $original = [['read', 20]];
my $shallow = [@$original];
$shallow->[0][1] = 30;
print "After shallow edit: $original->[0][1]\n";
my $rows = [map { [@$_] } @$original];
$rows->[0][1] = 40;
print "After row edit: $original->[0][1]\n";
print "Separate row: $rows->[0][1]\n";
Perl exercise C - Four real test cases

Try it first: Write four named tests for zero, ordinary input, the upper bound and a rejected negative value.

Installed core Test::More emits a plan and named TAP results. The four cases execute at runtime; perl -c does not run the test assertions. An unexpected failure produces a nonzero exit status.

Expected stdout:

1..4
ok 1 - zero
ok 2 - normal
ok 3 - upper boundary
ok 4 - negative rejected

Test record: passed; Perl 5.34.1; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

use strict;
use warnings;
use Test::More tests => 4;
sub double_minutes {
    my ($n) = @_;
    die "invalid minutes\n" unless defined($n) && !ref($n) &&
        $n =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $n <= 120;
    return $n * 2;
}
is(double_minutes(0), 0, 'zero');
is(double_minutes(20), 40, 'normal');
is(double_minutes(120), 240, 'upper boundary');
my $ok = eval { double_minutes(-1); 1 };
ok(!$ok && $@ eq "invalid minutes\n", 'negative rejected');

Expected syntax rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: Perl 01 - Scalars and context

Deliberately invalid source, never executed. Observed diagnostic category on the stated interpreter syntax checker: Global symbol.

use strict; print $missing;
Expected rejection: Perl 02 - Bounded control flow

Deliberately invalid source, never executed. Observed diagnostic category on the stated interpreter syntax checker: syntax error.

my $x = ;
Expected rejection: Perl 03 - Subroutines and validation

Deliberately invalid source, never executed. Observed diagnostic category on the stated interpreter syntax checker: declare constant item.

my (3) = (1);
Expected rejection: Perl 04 - Hashes and references

Deliberately invalid source, never executed. Observed diagnostic category on the stated interpreter syntax checker: syntax error.

my $x = [1, 2;
Tested learning pack

Swift Foundations

Core types, optionals, functions, collections, Unicode strings, value and reference semantics, errors, local source files and observable tests. No frameworks, concurrency, package manager or unsafe pointers.

Learners comfortable saving plain-text files and using a terminal. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Use /usr/bin/swiftc -swift-version 6 -warnings-as-errors "Example.swift" -o "Practice", then ./Practice in a new practice folder. Replace Example.swift with the exact exported filename. The companion example instead compiles main.swift and "Study tools.swift" together. The harness uses an owned temporary module cache. Apple Swift 6.4 on this Mac is the only tested compiler; Swift 6 mode is not a complete conformance claim. No Foundation, SwiftUI, SwiftPM, downloads or external inputs are required. The browser exports text and does not run Swift.

Configuration: Run instructions.txt
Use /usr/bin/swiftc -swift-version 6 -warnings-as-errors "Example.swift" -o "Practice", then ./Practice in a new practice folder. Replace Example.swift with the exact exported filename. The companion example instead compiles main.swift and "Study tools.swift" together. The harness uses an owned temporary module cache. Apple Swift 6.4 on this Mac is the only tested compiler; Swift 6 mode is not a complete conformance claim. No Foundation, SwiftUI, SwiftPM, downloads or external inputs are required. The browser exports text and does not run Swift.

1. Compile before running

A Swift source file is checked and compiled to an executable. Compile success does not establish correct output. This pack records both, with Swift 6 mode and warnings treated as errors. Deliberately invalid fixtures are never run. Optimization, other targets and the Swift interpreter are not tested.

2. Types, constants and optionals

let fixes a binding; var allows reassignment. Swift does not implicitly convert Int to Double. An Int? can contain a value or nil; use optional binding or a documented fallback instead of forcing it. Int conversion accepts a syntax, not an application policy, so validate bounds separately.

3. Control flow and functions

if requires Bool. switch must cover all possibilities, often with default. Functions have parameter types, argument labels and a return type. A function can return nil for rejected input when that contract is clear. Keep arithmetic within a stated range.

4. Collections and order

Arrays have order; dictionaries and sets do not promise a report order. Sort keys or values before printing. Array access outside its indices traps, so use first or check indices for uncertain positions. The examples contain tiny authored collections, not arbitrary workloads.

5. Strings and Unicode

String.count counts extended grapheme clusters represented as Character values; utf8.count counts encoded bytes. Indexing uses String.Index rather than an integer offset. Canonically equivalent spellings can compare equal. A character is not necessarily one byte or Unicode scalar.

6. Value and reference semantics

Assigning a struct creates a separate value; assigning a class instance copies its reference. let on a class reference does not freeze its mutable properties. Arrays of class references still refer to the same objects. Swift uses automatic reference counting for classes; cycles and weak/unowned design are outside these examples.

7. Recoverable errors

A throwing function declares throws and callers use try. do/catch handles matching errors. A failed precondition or out-of-range array access is a trap, not a recoverable error for catch. These programs validate input and avoid deliberate traps; expected compiler failures are a separate test category.

8. Files, modules and test evidence

The companion is compiled into the same executable, not imported as a separately built module. With multiple files, top-level entry statements are in main.swift. The assertion exercise uses explicit checks with fatalError only on unexpected results; those failure branches are not deliberately executed. No arbitrary submitted code is sandboxed.

Quick reference

Binding

let / var

Constant binding or mutable variable.

Types

Int / Double / Bool

Explicit numeric conversion; conditions require Bool.

Absence

Int? / nil

Optional value or absence.

Unwrap

if let / guard let

Safely bind a present optional.

Fallback

value ?? fallback

Supply a value when optional is nil.

Flow

if / switch / for

Choose branches and visit sequences.

Functions

func f(_ x: Int) -> Int

Typed argument and return; underscore omits call label.

Ranges

0...120 / 0..<3

Closed versus half-open ranges.

Arrays

[Int] / first / indices

Ordered collection with checked access.

Mappings

[String: Int] / keys.sorted()

Optional lookup and explicit output order.

Strings

count / utf8.count

Grapheme clusters versus UTF-8 bytes.

Values

struct

Copied value; reference-valued properties can still alias.

References

final class / ===

Identity of class instances.

Errors

Error / throws / try / catch

Model and handle recoverable failures.

Transforms

filter / map / reduce

Create selections, transformations and accumulated values.

Build

swiftc -swift-version 6

Compile in pinned language mode before executing.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Swift 01 - Typed values

Explicit conversion chooses floating-point division. The small positive input stays within Int range.

Expected stdout:

Ada: 25 minutes
Integer half: 12
Decimal half: 12.5

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

let name = "Ada"
let minutes: Int = 25
let half = Double(minutes) / 2
print("\(name): \(minutes) minutes")
print("Integer half: \(minutes / 2)")
print("Decimal half: \(half)")
Swift 02 - Optional conversion

Conversion and the application range are separate checks. This accepts Swift Int syntax, including a leading plus; it does not claim a digits-only policy.

Expected stdout:

25: 25
no: rejected
121: rejected

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

func minutes(_ text: String) -> Int? {
    guard let value = Int(text), (0...120).contains(value) else {
        return nil
    }
    return value
}
for text in ["25", "no", "121"] {
    if let value = minutes(text) {
        print("\(text): \(value)")
    } else { print("\(text): rejected") }
}
Swift 03 - Branches and loops

The default covers every remaining Int, including negative values. This classifier does not validate input.

Expected stdout:

0: none
20: short
45: outside short range

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

func band(_ value: Int) -> String {
    switch value {
    case 0: return "none"
    case 1...30: return "short"
    default: return "outside short range"
    }
}
for value in [0, 20, 45] { print("\(value): \(band(value))") }
Swift 04 - Function contracts

Argument labels explain call sites. Bounded operands avoid overflow, and nil denotes rejected input.

Expected stdout:

40
60
true

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

func scaled(minutes: Int, factor: Int = 2) -> Int? {
    guard (0...120).contains(minutes), (1...3).contains(factor) else {
        return nil
    }
    return minutes * factor
}
print(scaled(minutes: 20) ?? -1)
print(scaled(minutes: 20, factor: 3) ?? -1)
print(scaled(minutes: -1) == nil)
Swift 05 - Deterministic collections

Filtering keeps array order. Dictionary output is explicitly sorted; the lookup fallback is safe here because the keys came from this unchanged dictionary.

Expected stdout:

30, 20
Total: 60
coding: 40
reading: 20
Unique: 3

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

let sessions = [10, 30, 20]
let selected = sessions.filter { $0 >= 20 }
print(selected.map { String($0) }.joined(separator: ", "))
print("Total: \(sessions.reduce(0, +))")
let totals = ["reading": 20, "coding": 40]
for key in totals.keys.sorted() {
    print("\(key): \(totals[key] ?? 0)")
}
print("Unique: \(Set(sessions + [10]).count)")
Swift 06 - Text is not bytes

The combining accent joins the preceding letter as one Character. Canonical equivalence does not mean identical UTF-8 bytes.

Expected stdout:

Characters: 4
UTF-8 bytes: 6
Equivalent: true
First: C

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

let text = "Cafe\u{301}"
print("Characters: \(text.count)")
print("UTF-8 bytes: \(text.utf8.count)")
print("Equivalent: \(text == "Caf\u{e9}")")
if let first = text.first { print("First: \(first)") }
Swift 07 - Values and references

The struct is copied as a value. Both class bindings refer to the same instance; let prevents rebinding but permits this mutable property.

Expected stdout:

Values: 10, 20
References: 30, 30
Same object: true

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

struct ValueLog { var minutes: Int }
final class SharedLog {
    var minutes: Int
    init(_ minutes: Int) { self.minutes = minutes }
}
let original = ValueLog(minutes: 10)
var copy = original
copy.minutes = 20
let shared = SharedLog(10)
let alias = shared
alias.minutes = 30
print("Values: \(original.minutes), \(copy.minutes)")
print("References: \(shared.minutes), \(alias.minutes)")
print("Same object: \(shared === alias)")
Swift 08 - Recoverable errors

Only the explicit error is recoverable here. The final catch handles other errors allowed by the untyped throws contract instead of allowing them to propagate out of this entry point. No runtime trap is deliberately triggered.

Expected stdout:

40
rejected

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

enum StudyError: Error { case outsideRange }
func checkedDouble(_ value: Int) throws -> Int {
    guard (0...120).contains(value) else { throw StudyError.outsideRange }
    return value * 2
}
for value in [20, -1] {
    do { print(try checkedDouble(value)) }
    catch StudyError.outsideRange { print("rejected") }
    catch { print("unexpected error") }
}
Swift 09 - Compile local sources

Save both files together and compile main.swift plus "Study tools.swift" with the same flags. This is one executable built from two source files, not a separately imported library. studyTotal assumes its intermediate sums fit in Int; only the bounded authored values are demonstrated.

Expected stdout:

Companion: 60

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

print("Companion: \(studyTotal([10, 20, 30]))")

Companion: Study tools.swift

func studyTotal(_ values: [Int]) -> Int {
    return values.reduce(0, +)
}
Swift exercise A - Optional mean

Try it first: Compute a mean for up to ten minutes values in 0...120. Return nil for empty, oversized or invalid input.

An optional expresses that an empty or out-of-contract collection has no accepted mean. The input-size and value bounds also keep the sum small.

Expected stdout:

20.0
true

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

func mean(_ values: [Int]) -> Double? {
    guard !values.isEmpty, values.count <= 10,
          values.allSatisfy({ (0...120).contains($0) }) else { return nil }
    return Double(values.reduce(0, +)) / Double(values.count)
}
print(mean([10, 20, 30]) ?? -1)
print(mean([]) == nil)
Swift exercise B - Value copy

Try it first: Copy a one-row array of value records, edit the copied row and show that the original is unchanged.

Array and this struct have value semantics. Replacing Session with a class changes the aliasing behavior.

Expected stdout:

Original: 10
Edited: 20

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

struct Session { var title: String; var minutes: Int }
let original = [Session(title: "Read", minutes: 10)]
var edited = original
if !edited.isEmpty { edited[0].minutes = 20 }
print("Original: \(original.first?.minutes ?? 0)")
print("Edited: \(edited.first?.minutes ?? 0)")
Swift exercise C - Observable tests

Try it first: Test zero, normal input, upper bound and rejected negative input with observable failure on a mismatch.

All four checks execute at runtime. An unexpected result would terminate with a failure; the successful evidence does not claim that failure branch was executed.

Expected stdout:

Assertions: 4 passed

Test record: passed; Apple Swift 6.4; Swift 6 language mode; macOS 27.0.1 arm64; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

func doubleMinutes(_ value: Int) -> Int? {
    guard (0...120).contains(value) else { return nil }
    return value * 2
}
let cases: [(Int, Int?)] = [(0, 0), (20, 40), (120, 240), (-1, nil)]
var passed = 0
for (input, expected) in cases {
    guard doubleMinutes(input) == expected else { fatalError("wrong result") }
    passed += 1
}
print("Assertions: \(passed) passed")

Expected compiler rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: Swift 01 - Typed values

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: cannot convert value of type 'String'.

let minutes: Int = "25"
Expected rejection: Swift 02 - Optional conversion

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: must be unwrapped.

let value: Int? = nil
let required: Int = value
Expected rejection: Swift 07 - Values and references

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: cannot assign to value.

let minutes = 10
minutes = 20
Expected rejection: Swift 08 - Recoverable errors

Deliberately invalid source, never executed. Observed diagnostic category on the stated compiler: call can throw.

enum E: Error { case problem }
func fail() throws { throw E.problem }
fail()
Tested learning pack

Makefile Foundations

Build-language basics: targets, prerequisite graphs, timestamps, phony actions, variables, automatic variables, pattern rules, order-only prerequisites, failure and observable tests. Not a general-purpose language or a replacement shell tutorial.

Learners comfortable saving plain-text files and using a terminal. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

GNU Make 3.81 is the installed older implementation. Save each example and its companions in a separate NEW practice directory. Run /usr/bin/make -rR --no-print-directory -f "Example.mk" (replace the filename). Recipe lines begin with a literal tab. Outputs are fixed toy filenames inside that directory. Built-in rules/variables are disabled; /bin/sh runs recipes. Do not run untrusted makefiles, pass untrusted variable overrides or point at existing documents. make -n is NOT a sandbox: makefile evaluation, included files and recursive commands can execute code. No .ONESHELL, grouped targets, downloads, recursive builds or destructive clean targets are used.

Configuration: Run instructions.txt
GNU Make 3.81 is the installed older implementation. Save each example and its companions in a separate NEW practice directory. Run /usr/bin/make -rR --no-print-directory -f "Example.mk" (replace the filename). Recipe lines begin with a literal tab. Outputs are fixed toy filenames inside that directory. Built-in rules/variables are disabled; /bin/sh runs recipes. Do not run untrusted makefiles, pass untrusted variable overrides or point at existing documents. make -n is NOT a sandbox: makefile evaluation, included files and recursive commands can execute code. No .ONESHELL, grouped targets, downloads, recursive builds or destructive clean targets are used.

1. A build language and its executor

Makefile describes targets, prerequisites and recipes. GNU Make is the build tool executing that description; recipes use a shell. This pack tests GNU Make 3.81, not every Make dialect. Start each example in a separate new directory with only its supplied files.

2. Graphs and freshness

A normal target is rebuilt when missing or when a normal prerequisite has a newer modification time. Make compares timestamps, not file contents. Changing content while preserving an old timestamp may be missed. Each direct input belongs in the graph; a successful build does not prove complete dependencies.

3. Rules and phony actions

The first ordinary target is the default goal here. Write target: prerequisites, followed by tab-prefixed recipe lines. .PHONY marks actions that should run even if a same-named file exists. Do not make a phony target a normal prerequisite of a real file unless rebuilding each time is intentional.

4. Variables and expansion

With =, references expand when the variable is used; with :=, the right-hand side expands at assignment. Command-line assignments can override ordinary assignments. Expansion is not shell quoting: even quoted interpolated values can become dangerous when untrusted data contains shell syntax. All values here are fixed authored text.

5. Recipes and process boundaries

Each recipe line runs in a separate shell in this version. Join commands deliberately when state must persist. $$ passes a dollar sign through Make to the shell. A nonzero recipe exit stops that target and normally the build. Do not hide errors with a leading minus just to make the output appear successful.

6. Automatic and pattern variables

In a recipe, $@ names the target and $< names the first prerequisite. A %.out: %.in rule matches stems. These examples use fixed simple filenames without spaces; arbitrary path quoting and multi-output generator correctness require a separate design.

7. Order-only and failure semantics

Prerequisites after | must be available before a target is built, but their newer timestamp alone does not make the target stale. .DELETE_ON_ERROR requests deletion of a changed target after recipe failure; it is discussed, not used here. Our expected failure example writes no partial target.

8. Testing the graph

The harness runs each successful default target, checks outputs, repeats selected builds and changes controlled timestamps. A separate check expects a recipe failure and confirms dependents do not run. Invalid parser fixtures have no executable recipes. Neither -n nor a temporary folder is a security sandbox; only this authored material was exercised.

Quick reference

Rule

target: prerequisites

Names a graph edge and its recipe.

Recipe

TAB command

A real tab starts the command line.

Default

first ordinary target

Used when no goal is supplied in these examples.

Action

.PHONY: all test

Always considers these action targets out of date.

Expansion

NAME = $(OTHER)

Expand references later.

Snapshot

NAME := $(OTHER)

Expand the right side now.

Override

make NAME=value

Command-line assignments can override ordinary ones.

Target

$@

Current target name inside a recipe.

Input

$<

First prerequisite name in a recipe.

Pattern

%.out: %.in

Match a common filename stem.

Order only

target: input | stamp

Wait for stamp without using its age for freshness.

Dollar

$$name

Pass a dollar reference to the recipe shell.

Echo

@command

Suppress echo of this recipe, not its output.

Failure

nonzero exit status

Stop this target; dependents cannot succeed.

Inspect

make -n

Show most recipes; NOT safe for untrusted makefiles.

Pinned run

make -rR -f file.mk

Disable built-ins and choose this authored file.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Make 01 - Default and phony

The first ordinary target is the default. .PHONY ensures the action still runs if a file named all exists.

Expected stdout:

Goal: all

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all
all:
	@printf 'Goal: all\n'
Make 02 - Dependency graph

A missing report is built from the supplied input. The phony all action has no recipe and does not itself force report.txt to rebuild.

Expected stdout:

Built report

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all
all: report.txt
report.txt: input.txt
	@cp "$<" "$@"
	@printf 'Built report\n'

Companion: input.txt

minutes: 30
Make 03 - Expansion time

The recursively expanded variable sees the later LABEL; the simple variable captured the earlier text. Values are trusted literals.

Expected stdout:

second / first

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

LABEL = first
LATER = $(LABEL)
NOW := $(LABEL)
LABEL = second
.PHONY: all
all:
	@printf '%s / %s\n' '$(LATER)' '$(NOW)'
Make 04 - Automatic variables

Automatic variables are defined in the recipe context. Filenames are fixed simple toy names.

Expected stdout:

Target copied.txt from study.txt

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all
all: copied.txt
copied.txt: study.txt
	@cp "$<" "$@"
	@printf 'Target %s from %s\n' "$@" "$<"

Companion: study.txt

study
Make 05 - Pattern rule

One pattern rule serves two stems. Output order here assumes the default serial invocation; parallel builds are outside this evidence.

Expected stdout:

Built first.out
Built second.out

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all
all: first.out second.out
%.out: %.in
	@cp "$<" "$@"
	@printf 'Built %s\n' "$@"

Companion: first.in

one

Companion: second.in

two
Make 06 - Order-only prerequisite

The stamp must exist first. Its newer timestamp alone does not cause result.txt to rebuild.

Expected stdout:

Built result

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all
all: result.txt
result.txt: readiness.txt | ready.stamp
	@cp "$<" "$@"
	@printf 'Built result\n'
ready.stamp:
	@printf 'ready\n' > "$@"

Companion: readiness.txt

ready input
Make 07 - Recipe shell boundary

Make turns $$ into $. Each separate recipe line starts another shell, so the first line variable is absent from the second.

Expected stdout:

Same shell: study
Next shell: unset

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all
all:
	@word=study; printf 'Same shell: %s\n' "$$word"
	@printf 'Next shell: %s\n' "$${word-unset}"
Make 08 - Failure propagation

The default target succeeds. A separate harness invocation of after intentionally fails; the dependent recipe must not run. That failure is expected test evidence, not a successful build.

Expected stdout:

Normal check passed

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all check fail after
all: check
check:
	@printf 'Normal check passed\n'
after: fail
	@printf 'should not exist\n' > after.txt
fail:
	@printf 'Expected toy failure\n'
	@exit 7
Make 09 - Trusted configuration

The harness overrides LEVEL with one trusted literal. This recipe is not safe for arbitrary user-controlled override values; Make expansion precedes shell parsing.

Expected stdout:

Level: basic

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

LEVEL = basic
.PHONY: all
all:
	@printf 'Level: %s\n' '$(LEVEL)'
Make exercise A - Build then test

Try it first: Write a real file target and a separate phony test target that checks it.

The test depends on the output. cmp verifies its bytes; the build alone does not establish this assertion.

Expected stdout:

Built summary

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all test
all: summary.txt
summary.txt: lesson.txt
	@cp "$<" "$@"
	@printf 'Built summary\n'
test: summary.txt
	@cmp lesson.txt summary.txt
	@printf 'Test passed\n'

Companion: lesson.txt

practice: 20
Make exercise B - All direct inputs

Try it first: Combine two toy inputs and declare both as normal prerequisites.

Both input files are prerequisites. A changed second input must trigger a rebuild. Recipe filenames are explicit authored literals.

Expected stdout:

Built combined

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all
all: combined.txt
combined.txt: first.txt second.txt
	@cat first.txt second.txt > "$@"
	@printf 'Built combined\n'

Companion: first.txt

first

Companion: second.txt

second
Make exercise C - Observable assertions

Try it first: Make a test target that checks existence, nonempty output, content and an absent toy path.

Four shell test commands execute under Make. A failing check stops the target before the success message. The authored fresh directory makes absent.txt meaningful.

Expected stdout:

Assertions: 4 passed

Test record: passed; GNU Make 3.81; macOS 27.0.1 arm64; /bin/sh recipes; 2026-10-25. macOS 27.0.1 (arm64); Darwin 27.0.0

.PHONY: all test
all: test
toy.txt:
	@printf 'study\n' > "$@"
test: toy.txt
	@test -f toy.txt
	@test -s toy.txt
	@test "$$(cat toy.txt)" = study
	@test ! -e absent.txt
	@printf 'Assertions: 4 passed\n'

Expected parser rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: Make 01 - Default and phony

The Make parser rejected this authored fixture; no recipes were executed. Observed diagnostic category on the stated Make parser: missing separator.

all:
    printf bad
Expected rejection: Make 03 - Expansion time

The Make parser rejected this authored fixture; no recipes were executed. Observed diagnostic category on the stated Make parser: unterminated variable reference.

X = $(missing
all: $(X)
Expected rejection: Make 07 - Recipe shell boundary

The Make parser rejected this authored fixture; no recipes were executed. Observed diagnostic category on the stated Make parser: missing `endef'.

define NOTE
unfinished
Expected rejection: Make 09 - Trusted configuration

The Make parser rejected this authored fixture; no recipes were executed. Observed diagnostic category on the stated Make parser: missing `endif'.

ifeq (one,one)
all:
Tested learning pack

awk Foundations

Pattern/action processing, records and fields, validated numeric input, associative arrays, deterministic order, functions and reports. No CSV parser, GNU awk extensions, process execution or arbitrary file access.

Learners comfortable saving plain text and invoking an installed command-line tool. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Use the exact invocation beside each example. Export its .awk script and input companion into a new practice folder; LC_ALL=C pins byte-oriented ASCII behavior. /usr/bin/awk --version reports 20200816. Current upstream awk has features absent here; no --csv, GNU awk sorting functions or whole-POSIX conformance is claimed. All programs write stdout only. The browser exports text and never executes it. Do not interpolate untrusted text into an awk program; -v values also interpret backslash escapes and are not a raw-byte transport. Only fixed authored scripts and bounded toy inputs are tested.

Configuration: Run instructions.txt
Use the exact invocation beside each example. Export its .awk script and input companion into a new practice folder; LC_ALL=C pins byte-oriented ASCII behavior. /usr/bin/awk --version reports 20200816. Current upstream awk has features absent here; no --csv, GNU awk sorting functions or whole-POSIX conformance is claimed. All programs write stdout only. The browser exports text and never executes it. Do not interpolate untrusted text into an awk program; -v values also interpret backslash escapes and are not a raw-byte transport. Only fixed authored scripts and bounded toy inputs are tested.

1. Patterns and actions

awk is a text-processing language evaluated by the installed awk program. For each input record, matching rules run in source order. A missing pattern matches every record; a missing action prints the record. BEGIN runs before records and END runs afterward. These examples use explicit actions to make output predictable.

2. Records, fields and separators

With the default settings, newline separates records and FS=" " collapses runs of whitespace into fields. $0 is the whole record; $1 is the first field, NF the field count and NR the record count. A literal colon separator does not implement CSV quoting. Assigning a field can rebuild $0 using OFS.

3. Strings are not validated numbers

Arithmetic can convert strings and accept numeric prefixes, so coercion alone is not validation. The contract example checks one to three ASCII digits, then a value in 0..120. Values like 001 are accepted; signs, decimals and blanks are rejected. Totals are limited to at most 100 accepted records. Surrounding field whitespace is accepted; a blank record is rejected.

4. Arrays and report order

Associative arrays map string keys to values. for (key in array) does not guarantee report order. Store first-seen keys in a separate numbered array or use a fixed explicit order. The membership operator in distinguishes an absent key from a stored zero; avoid reading a missing element when testing existence.

5. Text matching and replacement

awk patterns use extended regular expressions. Anchors express whole-record or whole-field rules. index searches literal text; a string used as a dynamic regular expression has pattern semantics. sub and gsub mutate the selected text and return replacement counts. Replacement ampersands and backslashes have special meaning.

6. Functions and local names

Scalar parameters are passed by value; array parameters refer to the caller array. Names not declared as parameters are global. Extra trailing parameters can serve as local variables when omitted at the call. Keep the input contract explicit and avoid accidental shared global state.

7. Flow, exit and END

next skips remaining rules for this record. exit stops normal input processing, but END still runs. An error flag prevents END from printing a success report after rejection. A numeric exit status is separate from stdout. There is no claimed syntax-only sandbox: only fixed parser-failure fixtures are exercised.

8. Scope and safe practice

LC_ALL=C makes these ASCII and byte-level demonstrations reproducible; Unicode grapheme processing is outside this pack. Empty input is tested. No getline, system, pipes, output-file redirection, environment access or untrusted script generation is used. A temporary directory and test timeout are not an arbitrary-code sandbox.

Quick reference

Rule

pattern { action }

Run matching actions in source order.

Lifecycle

BEGIN / END

Before records and after input processing.

Record

$0 / NR

Whole current record and overall ordinal.

Fields

$1 / NF

First field and number of fields.

Separators

FS / OFS / ORS

Input fields, output fields and output records.

Output

print / printf

Use a fixed printf format for data.

Patterns

~ / !~ / ^ / $

Regex matching, negation and anchors.

Literal search

index(text, needle)

Return one-based position or zero.

Slice

substr(text, start, count)

One-based text slice.

Replacement

sub / gsub

First or all substitutions; returns count.

Map

totals[key]

Associative array access.

Presence

key in totals

Check membership without fetching a value.

Function

function f(x, local) {...}

Extra omitted parameters can be local names.

Skip

next

Continue with the next record.

Stop

exit 2

Stop input; END still runs.

Contract

regex then numeric range

Validate shape before numeric conversion.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

awk 01 - Records and fields

Default whitespace fields collapse spaces and tabs; the sample has exactly two fields per record.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk 01 Records and fields.awk" < "awk 01 Records and fields Input.txt"

Expected stdout:

row=1 fields=2 first=read last=20
row=2 fields=2 first=code last=40

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

{ printf "row=%d fields=%d first=%s last=%s\n", NR, NF, $1, $NF }

Companion: awk 01 Records and fields Input.txt

read 20
code 40
awk 02 - Match and select

The rule tests field count and a literal field value. It selects text rather than assuming the second field is numeric.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk 02 Match and select.awk" < "awk 02 Match and select Input.txt"

Expected stdout:

20
15

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

NF == 2 && $1 == "read" { print $2 }

Companion: awk 02 Match and select Input.txt

read 20
code 40
read 15
awk 03 - Field reconstruction

Assigning $1 rebuilds the record using OFS. A colon-delimited toy record has no quoting or escaping grammar; it is not CSV.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk 03 Field reconstruction.awk" < "awk 03 Field reconstruction Input.txt"

Expected stdout:

READ | 20
CODE | 40

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

BEGIN { FS = ":"; OFS = " | " }
NF == 2 { $1 = toupper($1); print $0 }

Companion: awk 03 Field reconstruction Input.txt

read:20
code:40
awk 04 - Validate before summing

All records must satisfy the bounded numeric contract. END still runs after exit, so failed suppresses a misleading total. Failure output is on stdout by this explicit toy contract.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk 04 Validate before summing.awk" < "awk 04 Validate before summing Input.txt"

Expected stdout:

Total: 60

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

function valid(s) {
    return s ~ /^[0-9]+$/ && length(s) <= 3 && (s + 0) <= 120
}
{
    if (NF != 1 || !valid($1) || NR > 100) {
        print "rejected"; failed = 1; exit 2
    }
    total += $1
}
END { if (!failed) printf "Total: %d\n", total }

Companion: awk 04 Validate before summing Input.txt

20
40
awk 05 - First-seen report order

The authored input is one nonempty word per record. Report order follows first occurrence, independent of associative-array iteration.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk 05 First-seen report order.awk" < "awk 05 First-seen report order Input.txt"

Expected stdout:

read: 2
code: 1
rest: 1

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

{
    if (!($1 in count)) order[++size] = $1
    count[$1]++
}
END {
    for (i = 1; i <= size; i++)
        printf "%s: %d\n", order[i], count[order[i]]
}

Companion: awk 05 First-seen report order Input.txt

read
code
read
rest
awk 06 - Missing versus zero

Membership is independent of the stored value. This does not fetch count["code"], which could create a missing element.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk 06 Missing versus zero.awk" < /dev/null

Expected stdout:

read present: 1
code present: 0
read value: 0

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

BEGIN {
    count["read"] = 0
    print "read present:", ("read" in count)
    print "code present:", ("code" in count)
    print "read value:", count["read"]
}
awk 07 - Literal search and replacement

index treats the dot literally. gsub uses a fixed regex and literal replacement text; arbitrary replacement escaping is outside this script.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk 07 Literal search and replacement.awk" < "awk 07 Literal search and replacement Input.txt"

Expected stdout:

5 | 2 | green.green
0 | 0 | red

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

{
    text = $0
    changes = gsub(/blue/, "green", text)
    printf "%d | %d | %s\n", index($0, "."), changes, text
}

Companion: awk 07 Literal search and replacement Input.txt

blue.blue
red
awk 08 - Function local state

The omitted trailing prefix parameter is local to this call; it does not modify the global prefix. Scalar arguments are passed by value.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk 08 Function local state.awk" < /dev/null

Expected stdout:

item: read
outer

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

function label(text, prefix) {
    prefix = "item"
    return prefix ": " text
}
BEGIN {
    prefix = "outer"
    print label("read")
    print prefix
}
awk 09 - Skip and finish

Only a hash at the beginning marks a comment; a whitespace-only record has NF zero. This exact convention is deliberate.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk 09 Skip and finish.awk" < "awk 09 Skip and finish Input.txt"

Expected stdout:

Kept: 2

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

/^#/ { next }
NF == 0 { next }
{ kept++ }
END { printf "Kept: %d\n", kept }

Companion: awk 09 Skip and finish Input.txt

# note
read

code
awk exercise A - Bounded mean

Try it first: Compute a mean for one to ten values in 0..120, report none for empty input, and reject malformed records.

The count guard prevents division by zero. Accepted inputs contain at most ten bounded values; formatting follows LC_ALL=C.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk exercise A Bounded mean.awk" < "awk exercise A Bounded mean Input.txt"

Expected stdout:

Mean: 20.0

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

function valid(s) {
    return s ~ /^[0-9]+$/ && length(s) <= 3 && (s + 0) <= 120
}
{
    if (NF != 1 || !valid($1) || NR > 10) {
        print "rejected"; failed = 1; exit 2
    }
    sum += $1; count++
}
END {
    if (!failed && count) printf "Mean: %.1f\n", sum / count
    else if (!failed) print "Mean: none"
}

Companion: awk exercise A Bounded mean Input.txt

10
20
30
awk exercise B - Stable unique lines

Try it first: Print each distinct whole line once, preserving its first occurrence.

The entire line is the key. Blank lines are valid data here and appear once; order follows input. The corpus is tiny, so unbounded memory growth is not addressed.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk exercise B Stable unique lines.awk" < "awk exercise B Stable unique lines Input.txt"

Expected stdout:

read
code
rest

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

!($0 in seen) { seen[$0] = 1; print $0 }

Companion: awk exercise B Stable unique lines Input.txt

read
code
read
rest
awk exercise C - Observable assertions

Try it first: Write checks for zero, upper bound, out-of-range input and numeric-prefix text.

The four checks run inside BEGIN. A mismatch exits nonzero before the final success line. This is a small observable test example, not a complete framework.

Invocation:

LC_ALL=C /usr/bin/awk -f "awk exercise C Observable assertions.awk" < /dev/null

Expected stdout:

Assertions: 4 passed

Test record: passed; awk 20200816; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

function valid(s) {
    return s ~ /^[0-9]+$/ && length(s) <= 3 && (s + 0) <= 120
}
function check(actual, expected) {
    if (actual != expected) { print "test failed"; exit 1 }
    passed++
}
BEGIN {
    check(valid("0"), 1)
    check(valid("120"), 1)
    check(valid("121"), 0)
    check(valid("12x"), 0)
    printf "Assertions: %d passed\n", passed
}

Expected parser rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: awk 01 - Records and fields

The parser rejected this authored fixture; no successful text transformation is claimed. Observed diagnostic category on the stated awk parser: syntax error.

BEGIN { print ( }
Expected rejection: awk 04 - Validate before summing

The parser rejected this authored fixture; no successful text transformation is claimed. Observed diagnostic category on the stated awk parser: non-terminated string.

BEGIN { x = "unfinished
Expected rejection: awk 07 - Literal search and replacement

The parser rejected this authored fixture; no successful text transformation is claimed. Observed diagnostic category on the stated awk parser: nonterminated character class.

/[/ { print }
Expected rejection: awk 08 - Function local state

The parser rejected this authored fixture; no successful text transformation is claimed. Observed diagnostic category on the stated awk parser: syntax error.

function broken( { return 1 }
Tested learning pack

sed Foundations

Addressed stream editing, BRE/ERE distinctions, substitution and escaping, ranges, branching, pattern/hold spaces and bounded multiline examples. No in-place editing, file-write commands, arbitrary scripts or general data parsing.

Learners comfortable saving plain text and invoking an installed command-line tool. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Use the exact invocation beside each example, including -n or -E where shown. Export the .sed script and input companion into a new practice folder. /usr/bin/sed is the macOS implementation; no independent version number is advertised, so the evidence pins OS and binary SHA-256. LC_ALL=C limits examples to ASCII byte behavior. Input files are read-only and outputs go to stdout. No -i/-I, w/r commands, executable extensions or arbitrary script interpolation are used. GNU sed behavior and complete POSIX conformance are not claimed. Empty output and exit zero can simply mean no match.

Configuration: Run instructions.txt
Use the exact invocation beside each example, including -n or -E where shown. Export the .sed script and input companion into a new practice folder. /usr/bin/sed is the macOS implementation; no independent version number is advertised, so the evidence pins OS and binary SHA-256. LC_ALL=C limits examples to ASCII byte behavior. Input files are read-only and outputs go to stdout. No -i/-I, w/r commands, executable extensions or arbitrary script interpolation are used. GNU sed behavior and complete POSIX conformance are not claimed. Empty output and exit zero can simply mean no match.

1. The editing cycle

sed is a text-transformation language executed by a stream editor. Ordinarily it reads one line into pattern space, applies commands in order and prints the result. The terminating input newline is handled separately. -n suppresses default printing; p explicitly prints. A successful command can produce no output.

2. Addresses choose records

A number selects a line, $ selects the last line, and a regex address selects matching pattern spaces. Two addresses select an inclusive range. For a regex second address, matching starts on a later line than the opening match. If the closing marker never arrives, the range continues to end of input.

3. Regex mode must be explicit

This implementation defaults to basic regular expressions; -E selects extended syntax. Parentheses and + have different roles between modes. These fixed patterns use ASCII and LC_ALL=C. Shell quoting, sed delimiters, regex escapes and replacement escapes are different layers; combining them carelessly changes the program.

4. Substitution and literal data

s/pattern/replacement/ replaces the first match; g requests all matches. An ampersand in replacement inserts the matched text, and escaped backreferences refer to capture groups. Escape an ampersand to insert it literally. Never build a sed program by concatenating untrusted search or replacement text.

5. Flow and output

d removes pattern space and starts the next cycle. b branches to a label or the script end; t branches when a substitution has succeeded since the relevant reset. Branches in this pack are forward-only so no unbounded loop is introduced. Duplicated output often means both p and default printing were enabled.

6. Hold space is separate state

h copies pattern space to hold space, g copies it back, and x exchanges them. G appends a newline and hold space. The fixed-label example keeps only one small value and does not accumulate an entire input file. State persists between cycles within one process.

7. Multiline work stays bounded

N appends the next input line with an embedded newline. P prints only the first segment while D can restart with remaining segments. This pack demonstrates only fixed two-line combinations, guarded at the last line. A parser for CSV, JSON or nested structured text belongs elsewhere.

8. Safety and implementation limits

No example edits its input file or uses file-write commands. -n is an output option, not a sandbox: sed scripts can have file side effects on implementations supporting such commands. Error diagnostics are implementation-specific. Resource limits and fresh directories constrain these authored tests, not arbitrary submitted scripts.

Quick reference

Run

sed -f script.sed

Read commands from a fixed script file.

Printing

-n / p

Suppress automatic output; print explicitly.

Address

2 / $ / /pattern/

Select a line, last line or match.

Range

/BEGIN/,/END/

Inclusive range with stated reopening behavior.

Delete

d

Start a new cycle without this pattern space.

Substitute

s/a/b/ / s/a/b/g

First match or every match.

Matched text

& in replacement

Insert the whole match; escape for a literal &.

BRE group

\(group\) / \1

Capture and reference in default mode.

ERE mode

-E / (group) / +

Extended syntax; pin the invocation.

Command group

address { ... }

Apply a group only to selected pattern spaces.

Copy state

h / g

Copy pattern to hold space or back.

Swap state

x

Exchange pattern and hold space.

Append state

G

Append newline plus hold space.

Next line

N

Append one line with an embedded newline.

Branch

b label / :label

Jump forward in these bounded examples.

Conditional branch

t label

Branch on a successful substitution since reset.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

sed 01 - Select lines

-n makes output come only from p. With two input lines, line 2 also satisfies $, so it prints twice; commands are independent.

Invocation:

LC_ALL=C /usr/bin/sed -n -f "sed 01 Select lines.sed" < "sed 01 Select lines Input.txt"

Expected stdout:

beta
gamma

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

2p
$p

Companion: sed 01 Select lines Input.txt

alpha
beta
gamma
sed 02 - Delete addressed lines

Deletion changes only output. A leading-space hash is retained because the comment rule requires # in column one.

Invocation:

LC_ALL=C /usr/bin/sed -f "sed 02 Delete addressed lines.sed" < "sed 02 Delete addressed lines Input.txt"

Expected stdout:

read
code

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

/^#/d
/^[[:space:]]*$/d

Companion: sed 02 Delete addressed lines Input.txt


# note
read
  
code
sed 03 - First and global replacement

Commands run in order on the same pattern space. The first substitution changes one blue; the second changes every red.

Invocation:

LC_ALL=C /usr/bin/sed -f "sed 03 First and global replacement.sed" < "sed 03 First and global replacement Input.txt"

Expected stdout:

green blue orange orange

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

s/blue/green/
s/red/orange/g

Companion: sed 03 First and global replacement Input.txt

blue blue red red
sed 04 - Matched text and literal ampersand

The first command wraps only the first digit run in brackets using &. The second command inserts a literal ampersand. The pattern and replacement are fixed authored syntax.

Invocation:

LC_ALL=C /usr/bin/sed -f "sed 04 Matched text and literal ampersand.sed" < "sed 04 Matched text and literal ampersand Input.txt"

Expected stdout:

task [25] & 5

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

s/[0-9][0-9]*/[&]/
s/PLUS/\&/g

Companion: sed 04 Matched text and literal ampersand Input.txt

task 25 PLUS 5
sed 05 - Basic capture groups

Default BRE uses escaped grouping parentheses. Anchors require the full toy record; unmatched lines pass through unchanged.

Invocation:

LC_ALL=C /usr/bin/sed -f "sed 05 Basic capture groups.sed" < "sed 05 Basic capture groups Input.txt"

Expected stdout:

20 minutes for read
40 minutes for code
invalid

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

s/^\([a-z][a-z]*\):\([0-9][0-9]*\)$/\2 minutes for \1/

Companion: sed 05 Basic capture groups Input.txt

read:20
code:40
invalid
sed 06 - Extended capture groups

-E enables the unescaped parentheses and + syntax used here. The tested replacement backreference syntax remains a backslash plus digit.

Invocation:

LC_ALL=C /usr/bin/sed -E -f "sed 06 Extended capture groups.sed" < "sed 06 Extended capture groups Input.txt"

Expected stdout:

20 minutes for read
40 minutes for code

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

s/^([a-z]+):([0-9]+)$/\2 minutes for \1/

Companion: sed 06 Extended capture groups Input.txt

read:20
code:40
sed 07 - Inclusive marker range

The matching marker lines are included. -n prevents outside lines from being automatically printed. Missing END keeps the range open to EOF.

Invocation:

LC_ALL=C /usr/bin/sed -n -f "sed 07 Inclusive marker range.sed" < "sed 07 Inclusive marker range Input.txt"

Expected stdout:

BEGIN
read
END

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

/^BEGIN$/,/^END$/p

Companion: sed 07 Inclusive marker range Input.txt

skip
BEGIN
read
END
skip
sed 08 - Remember a fixed label

The first line is copied into hold space and not printed. Each later line appends that label. This holds one bounded label rather than accumulating the stream.

Invocation:

LC_ALL=C /usr/bin/sed -f "sed 08 Remember a fixed label.sed" < "sed 08 Remember a fixed label Input.txt"

Expected stdout:

read | Study
code | Study

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

1 {
h
d
}
G
s/\n/ | /

Companion: sed 08 Remember a fixed label Input.txt

Study
read
code
sed 09 - Join two-line groups

N is skipped on the final unpaired line. This pairs records, not quoted CSV rows or arbitrary multiline structures.

Invocation:

LC_ALL=C /usr/bin/sed -f "sed 09 Join two-line groups.sed" < "sed 09 Join two-line groups Input.txt"

Expected stdout:

read | 20
code | 40

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

$!N
s/\n/ | /

Companion: sed 09 Join two-line groups Input.txt

read
20
code
40
sed exercise A - Bounded forward branch

Try it first: Uppercase exactly read or code, leave other whole lines unchanged, and use a forward branch.

A successful first substitution branches forward to done. Every path reaches the end without looping; the next record starts a fresh cycle.

Invocation:

LC_ALL=C /usr/bin/sed -f "sed exercise A Bounded forward branch.sed" < "sed exercise A Bounded forward branch Input.txt"

Expected stdout:

READ
CODE
rest

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

s/^read$/READ/
t done
s/^code$/CODE/
:done

Companion: sed exercise A Bounded forward branch Input.txt

read
code
rest
sed exercise B - Trim and select

Try it first: Trim line edges, select lines beginning task:, remove that prefix and print the remaining text once.

-n plus the addressed block prints selected lines once. Trimming here follows C-locale whitespace, not a Unicode normalization policy.

Invocation:

LC_ALL=C /usr/bin/sed -n -f "sed exercise B Trim and select.sed" < "sed exercise B Trim and select Input.txt"

Expected stdout:

read
code

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

s/^[[:space:]]*//
s/[[:space:]]*$//
/^task:/ {
s/^task:[[:space:]]*//
p
}

Companion: sed exercise B Trim and select Input.txt

  task: read  
ignore
	task: code	
sed exercise C - Four observable cases

Try it first: Rewrite only complete item=<digits> records. Predict zero, multiple digits, empty value and numeric-prefix text.

These are four input/output cases, not four embedded assertions inside sed. The external harness checks exact output. The regex accepts digit strings of any length; it does not enforce the awk pack numeric range.

Invocation:

LC_ALL=C /usr/bin/sed -f "sed exercise C Four observable cases.sed" < "sed exercise C Four observable cases Input.txt"

Expected stdout:

value:0
value:120
item=
item=12x

Test record: passed; macOS /usr/bin/sed; macOS 27.0.1 arm64; LC_ALL=C; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

s/^item=\([0-9][0-9]*\)$/value:\1/

Companion: sed exercise C Four observable cases Input.txt

item=0
item=120
item=
item=12x

Expected parser rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: sed 01 - Select lines

The parser rejected this authored fixture; no successful text transformation is claimed. Observed diagnostic category on the stated sed parser: unescaped newline inside substitute pattern.

s/alpha/beta
Expected rejection: sed 05 - Basic capture groups

The parser rejected this authored fixture; no successful text transformation is claimed. Observed diagnostic category on the stated sed parser: unbalanced brackets.

/[/p
Expected rejection: sed 07 - Inclusive marker range

The parser rejected this authored fixture; no successful text transformation is claimed. Observed diagnostic category on the stated sed parser: undefined label.

b absent
Expected rejection: sed 09 - Join two-line groups

The parser rejected this authored fixture; no successful text transformation is claimed. Observed diagnostic category on the stated sed parser: extra characters.

q garbage
Tested learning pack

jq Foundations

JSON query language: filter streams, projection, selection, null/presence, data parameters, grouping, aggregation, updates and explicit validation. This is beyond parsing JSON; no remote data or schema conformance claim.

Learners comfortable saving plain text and invoking an installed command-line tool. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Export the fixed .jq program and companion input. /usr/bin/jq --version reports jq-1.7.1-apple; the upstream 1.7 manual is context, not proof of every Apple-build behavior. -c makes JSON output compact. -r would remove JSON quoting from string outputs and is not used here. Programs are trusted and inputs tiny. Use --arg or --argjson for data, never concatenate data into program text. No modules, environment access, external files or network commands are used. The HTML only exports text. -e result statuses and deliberate compile/runtime errors are separate outcomes. Numeric examples use small finite integers; exact large-integer or financial arithmetic is outside scope.

Configuration: Run instructions.txt
Export the fixed .jq program and companion input. /usr/bin/jq --version reports jq-1.7.1-apple; the upstream 1.7 manual is context, not proof of every Apple-build behavior. -c makes JSON output compact. -r would remove JSON quoting from string outputs and is not used here. Programs are trusted and inputs tiny. Use --arg or --argjson for data, never concatenate data into program text. No modules, environment access, external files or network commands are used. The HTML only exports text. -e result statuses and deliberate compile/runtime errors are separate outcomes. Numeric examples use small finite integers; exact large-integer or financial arithmetic is outside scope.

1. A filter may produce many results

A jq filter consumes a JSON value and can emit zero, one or many values. .items[] emits each array element; enclosing that stream in brackets collects it. A pipe feeds every result to the next filter. Know whether the intended output is one array or several JSON texts.

2. Choose fields and keep their types

Object projection constructs a new object. Accessing an absent object member produces null, which differs from a false value or zero. has tests whether a member exists. A field lookup alone does not validate the shape of its parent object.

3. Selection follows a contract

select keeps or discards the current value; map runs its filter for each array element and collects every emitted result. The selection and grouping examples assume correctly typed records. Comparisons can order values of different types, so a threshold comparison alone is not numeric validation.

4. Missing, null and false need a policy

The // fallback treats both null and false as absent results. It does not replace zero or an empty string. Use an explicit condition when false must be preserved, and has when missing must be distinguished from a present null.

5. Pass data without constructing source

Keep the filter in a .jq file. --arg binds a string; --argjson parses a JSON value. They do not splice values into jq syntax. Shell quoting remains a separate layer. Malformed --argjson data is a command failure, not a filter compile error.

6. Aggregation and order are deliberate

-s collects all input JSON texts into one array, so it is bounded here rather than advertised as a large-data technique. group_by sorts groups by the grouping key. reduce carries an explicit accumulator through a stream; duplicate keys need an intentional merge policy.

7. Validate before calculation

The bounded total accepts an array of at most ten integral numeric values from zero through 120. It rejects strings, booleans and out-of-range values using error. An empty array has total zero. This small contract is not JSON Schema validation.

8. Results and status are separate evidence

Without -e, no output can still be successful. With -e, false/null as the last result returns status 1 and no result returns 4. A compiler rejection and a runtime error are different. Test bytes, result count and status; never treat successful parsing as permission to execute arbitrary code.

Quick reference

Identity

.

Return the current input.

Field

.task.name

Read an object member along a path.

Iteration

.items[]

Emit each array element as a separate result.

Collection

[filter]

Collect all results into one array.

Projection

{name, minutes}

Construct an object from selected members.

Selection

select(condition)

Keep the current value only when the condition is truthy.

Mapping

map(filter)

Apply a filter across an array.

Presence

has("enabled")

Test whether an object member exists.

Fallback

value // default

Fallback for null or false, not for zero.

Parameters

--arg / --argjson

Pass a string or parsed JSON data value.

Input collection

-s

Read all input JSON texts into one array.

Grouping

group_by(.kind)

Group and order by the key.

Reduction

reduce stream as $x (init; step)

Accumulate a stream with explicit state.

Update

path |= filter

Return a value with the selected path transformed.

Contract

type / floor / all / error

Check the small accepted domain and reject violations.

Status

-e

Make false/null or no-result outcomes nonzero.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

jq 01 - Project typed fields

Projection retains the numeric type. A missing object member yields null.

Invocation:

/usr/bin/jq -c -f 'jq 01 Project typed fields.jq' < 'jq 01 Project typed fields Input.json'

Expected stdout:

{"name":"read","minutes":20,"missing":null}

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

{name: .task.name, minutes: .task.minutes, missing: .absent}

Companion: jq 01 Project typed fields Input.json

{"task":{"name":"read","minutes":20}}
jq 02 - Streams and arrays

This produces two JSON string results, not one array. The companion must contain an items array.

Invocation:

/usr/bin/jq -c -f 'jq 02 Streams and arrays.jq' < 'jq 02 Streams and arrays Input.json'

Expected stdout:

"read"
"code"

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

.items[] | .name

Companion: jq 02 Streams and arrays Input.json

{"items":[{"name":"read"},{"name":"code"}]}
jq 03 - Select records

The records already satisfy a small schema: name is text and minutes a small number. Selection is not a schema validator.

Invocation:

/usr/bin/jq -c -f 'jq 03 Select records.jq' < 'jq 03 Select records Input.json'

Expected stdout:

[{"name":"read","minutes":20}]

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

[.items[] | select(.minutes >= 20) | {name, minutes}]

Companion: jq 03 Select records Input.json

{"items":[{"name":"read","minutes":20},{"name":"rest","minutes":5}]}
jq 04 - False null and missing

The fallback replaces false. The explicit condition preserves it; has distinguishes a missing member from a present null.

Invocation:

/usr/bin/jq -c -f 'jq 04 False null and missing.jq' < 'jq 04 False null and missing Input.json'

Expected stdout:

{"fallback":true,"present":true,"preserved":false}

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

{fallback: (.enabled // true), present: has("enabled"), preserved: (if .enabled == null then true else .enabled end)}

Companion: jq 04 False null and missing Input.json

{"enabled":false}
jq 05 - Parameters remain data

--arg keeps punctuation in a string. --argjson passes a numeric threshold. The fixed filter is never constructed from either value.

Invocation:

/usr/bin/jq -c --arg label 'Study & learn' --argjson minimum 20 -f 'jq 05 Parameters remain data.jq' < 'jq 05 Parameters remain data Input.json'

Expected stdout:

{"label":"Study & learn","names":["read"]}

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

{label: $label, names: [.items[] | select(.minutes >= $minimum) | .name]}

Companion: jq 05 Parameters remain data Input.json

{"items":[{"name":"read","minutes":20},{"name":"rest","minutes":5}]}
jq 06 - Collect a tiny JSON stream

-s collects two JSON texts before evaluation. The sum assumes numeric minutes; an empty stream produces an empty array and total zero.

Invocation:

/usr/bin/jq -c -s -f 'jq 06 Collect a tiny JSON stream.jq' < 'jq 06 Collect a tiny JSON stream Input.json'

Expected stdout:

{"count":2,"total":60}

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

{count: length, total: (map(.minutes) | add // 0)}

Companion: jq 06 Collect a tiny JSON stream Input.json

{"minutes":20}
{"minutes":40}
jq 07 - Group and aggregate

Groups are ordered by kind, so break comes first even though work appeared first in the input. The records are already typed.

Invocation:

/usr/bin/jq -c -f 'jq 07 Group and aggregate.jq' < 'jq 07 Group and aggregate Input.json'

Expected stdout:

[{"kind":"break","total":5},{"kind":"work","total":60}]

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

.items | group_by(.kind) | map({kind: .[0].kind, total: (map(.minutes) | add)})

Companion: jq 07 Group and aggregate Input.json

{"items":[{"kind":"work","minutes":20},{"kind":"break","minutes":5},{"kind":"work","minutes":40}]}
jq 08 - Validate a bounded total

Only at most ten integral numbers from zero through 120 are accepted. Boolean, string and nonintegral numeric inputs are rejected before a total is returned.

Invocation:

/usr/bin/jq -c -f 'jq 08 Validate a bounded total.jq' < 'jq 08 Validate a bounded total Input.json'

Expected stdout:

{"total":60}

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

def valid: type == "number" and . >= 0 and . <= 120 and floor == .;
if type != "array" then error("expected array")
elif length > 10 then error("too many values")
elif all(.[]; valid) then {total: (add // 0)}
else error("invalid value") end

Companion: jq 08 Validate a bounded total Input.json

[20,40]
jq 09 - Return an updated value

The output adds or replaces done for each task. jq does not rewrite the input file; fields outside the selected path are retained.

Invocation:

/usr/bin/jq -c -f 'jq 09 Return an updated value.jq' < 'jq 09 Return an updated value Input.json'

Expected stdout:

{"tasks":[{"name":"read","minutes":20,"done":false},{"name":"rest","minutes":0,"done":true}]}

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

.tasks |= map(. + {done: (.minutes == 0)})

Companion: jq 09 Return an updated value Input.json

{"tasks":[{"name":"read","minutes":20},{"name":"rest","minutes":0}]}
jq exercise A - Pending names

Try it first: Return an array of names for explicitly unfinished items, in sorted order.

Only an explicit false value is selected; a missing done field becomes null and does not match. Sorting is deliberate.

Invocation:

/usr/bin/jq -c -f 'jq exercise A Pending names.jq' < 'jq exercise A Pending names Input.json'

Expected stdout:

["read","write"]

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

[.items[] | select(.done == false) | .name] | sort

Companion: jq exercise A Pending names Input.json

{"items":[{"name":"write","done":false},{"name":"read","done":false},{"name":"rest","done":true}]}
jq exercise B - Merge duplicate names

Try it first: Aggregate minutes by name without silently replacing an earlier value.

The object accumulator deliberately sums duplicate names. These fixed records have string names and small numeric minutes.

Invocation:

/usr/bin/jq -c -f 'jq exercise B Merge duplicate names.jq' < 'jq exercise B Merge duplicate names Input.json'

Expected stdout:

{"read":60,"rest":5}

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

reduce .[] as $row ({}; .[$row.name] = ((.[$row.name] // 0) + $row.minutes))

Companion: jq exercise B Merge duplicate names Input.json

[{"name":"read","minutes":20},{"name":"read","minutes":40},{"name":"rest","minutes":5}]
jq exercise C - Four observable checks

Try it first: Check zero, the upper boundary, an out-of-range value and numeric-prefix text.

The program compares all four results with an explicit expectation and raises an error on a mismatch. This is a toy test, not a testing framework.

Invocation:

/usr/bin/jq -c -n -f 'jq exercise C Four observable checks.jq' < /dev/null

Expected stdout:

{"checks":4,"status":"passed"}

Test record: passed; jq-1.7.1-apple; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

def valid: type == "number" and . >= 0 and . <= 120 and floor == .;
[0,120,121,"12x"] | map(valid) as $actual
| if $actual == [true,true,false,false] then {checks:4, status:"passed"}
  else error("test failed") end

Expected program rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: jq 01 - Project typed fields

The stated processor rejected this authored fixture; no successful transformation is claimed. Observed diagnostic category on the stated jq compiler: compile error.

.task |
Expected rejection: jq 05 - Parameters remain data

The stated processor rejected this authored fixture; no successful transformation is claimed. Observed diagnostic category on the stated jq compiler: compile error.

def broken(: .;
Expected rejection: jq 08 - Validate a bounded total

The stated processor rejected this authored fixture; no successful transformation is claimed. Observed diagnostic category on the stated jq compiler: compile error.

[1,
Expected rejection: jq exercise B - Merge duplicate names

The stated processor rejected this authored fixture; no successful transformation is claimed. Observed diagnostic category on the stated jq compiler: not defined.

not_a_defined_function
Tested learning pack

XSLT 1.0 Foundations

XSLT 1.0 transformation language: templates, XPath 1.0 selections, namespaces, sorting, parameters, variables, named templates, identity transforms, keys and explicit input checks. Supporting XPath expressions do not constitute a standalone XPath pack. No XSLT 2.0/3.0, extension functions or arbitrary documents.

Learners comfortable saving plain text and invoking an installed command-line tool. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Export the fixed .xsl stylesheet and XML companion. The installed xsltproc reports libxslt 1.1.35 and libxml2 2.9.13; these old installed versions are a recorded learning environment, not a recommendation for untrusted-document processing. Every command uses --nonet --novalid --nowrite --nomkdir plus small depth/variable limits and empty catalogue environment variables. These flags are defense in depth, not a complete sandbox: local file reads can exist in other stylesheets. This pack has no DTD declarations, custom/external entities, document(), imports, includes, extensions or secondary output. Only authored toy XML and trusted stylesheets are tested. The HTML never runs them. Output is stdout; inputs remain unchanged. XPath 1.0 syntax is introduced only as needed by XSLT; the standalone XPath entry stays planned. Installed --stringparam cannot transport a value containing both single and double quotes: it exits with status 8. That documented CLI limitation is tested separately; no quote workaround is implied.

Configuration: Run instructions.txt
Export the fixed .xsl stylesheet and XML companion. The installed xsltproc reports libxslt 1.1.35 and libxml2 2.9.13; these old installed versions are a recorded learning environment, not a recommendation for untrusted-document processing. Every command uses --nonet --novalid --nowrite --nomkdir plus small depth/variable limits and empty catalogue environment variables. These flags are defense in depth, not a complete sandbox: local file reads can exist in other stylesheets. This pack has no DTD declarations, custom/external entities, document(), imports, includes, extensions or secondary output. Only authored toy XML and trusted stylesheets are tested. The HTML never runs them. Output is stdout; inputs remain unchanged. XPath 1.0 syntax is introduced only as needed by XSLT; the standalone XPath entry stays planned. Installed --stringparam cannot transport a value containing both single and double quotes: it exits with status 8. That documented CLI limitation is tested separately; no quote workaround is implied.

1. Templates build an output tree or text

XSLT is a transformation language, and xsltproc is the processor executing it. A template with match="/" starts at the document root. xsl:apply-templates dispatches selected nodes to matching templates. The authored stylesheet controls what is emitted; source elements are not automatically copied.

2. Context determines an XPath expression

In a root template, /tasks/task selects task elements below tasks. Inside a task template, @name reads that task attribute. Predicates filter node sets; position depends on the selected context. This pack uses XPath 1.0 only, without claiming a complete XPath introduction.

3. Namespaces are part of an element name

A default namespace in the source does not make unprefixed XPath names select those elements. Bind an explicit stylesheet prefix to the same namespace URI. The source may use a different prefix; namespace URI and local name determine the match.

4. Sort and branch explicitly

xsl:sort orders the selected nodes. data-type="number" distinguishes numeric sorting from text sorting. xsl:choose selects the first matching branch; xsl:if conditionally emits content. Missing values and invalid numeric text need an explicit policy.

5. Parameters are data with a type boundary

A global xsl:param accepts a caller-supplied value. xsltproc --stringparam passes text rather than an XPath expression. Never build stylesheet syntax from input strings. Parameters in this pack do not select files or external resources. On this installed CLI, a value containing both single and double quotes is rejected with status 8; --stringparam is not arbitrary-string transport.

6. Variables and templates have different jobs

A variable declared with select holds the expression value, such as a number or node set. In XSLT 1.0, content-created variables are result tree fragments with navigation restrictions. Named templates receive xsl:with-param values; they are used here without recursion.

7. Serialization and grouping need care

XML output escapes text and attributes for XML syntax. Copying with an identity template preserves a tree, not exact source bytes or formatting. Keys index source nodes; the grouping exercise picks one representative per kind and aggregates its group. Output order remains explicit.

8. Fixed inputs and observed failures

The total exercise rejects invalid digit attributes and too many records using a terminating message. Other examples assume their documented schema. Disable network and writes, keep inputs tiny, and reject DTDs/imports rather than trusting flags as a sandbox. Parser, stylesheet compilation and runtime termination are separate outcomes.

Quick reference

Stylesheet

xsl:stylesheet version="1.0"

Declare the supported transformation version.

Root

xsl:template match="/"

Handle the document root.

Dispatch

xsl:apply-templates select="..."

Process selected nodes with matching templates.

Value

xsl:value-of select="..."

Emit the XPath string value.

Literal text

xsl:text

Make exact text and whitespace explicit.

Namespace

xmlns:d="urn:atlas:tasks"

Bind a prefix for namespaced selection.

Sort

xsl:sort data-type="number"

Use numeric rather than lexical ordering.

Condition

xsl:if / xsl:choose

Emit conditional output or choose a branch.

Parameter

xsl:param / --stringparam

Pass text as data to the stylesheet.

Variable

xsl:variable select="..."

Bind the expression value within scope.

Named template

xsl:call-template / xsl:with-param

Invoke a named reusable template.

Copy

xsl:copy / @*|node()

Build a shallow copy and process descendants.

Key

xsl:key / key(...)

Index source nodes for local grouping.

Identity

generate-id(node)

Compare identity of nodes within this transformation.

Failure

xsl:message terminate="yes"

Stop with an explicit diagnostic.

Output

xsl:output method="text|xml"

Choose serialized text or XML output.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

XSLT 01 - Root and value

The document-root template counts task elements. It emits text, not an XML wrapper.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT 01 Root and value.xsl' 'XSLT 01 Root and value Input.xml'

Expected stdout:

2 tasks

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
  <xsl:value-of select="count(/tasks/task)"/><xsl:text> tasks&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT 01 Root and value Input.xml

<tasks><task name="read"/><task name="code"/></tasks>
XSLT 02 - Dispatch by context

The task template sees a task node, so @name is relative to that node. No other source text is selected.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT 02 Dispatch by context.xsl' 'XSLT 02 Dispatch by context Input.xml'

Expected stdout:

read
code

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
  <xsl:apply-templates select="/tasks/task"/>
</xsl:template>
<xsl:template match="task">
  <xsl:value-of select="@name"/><xsl:text>&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT 02 Dispatch by context Input.xml

<tasks><task name="read"/><task name="code"/></tasks>
XSLT 03 - Numeric sort and selection

The filter and sort assume small numeric attributes. Invalid numeric text does not pass the comparison, but that is not a validation report.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT 03 Numeric sort and selection.xsl' 'XSLT 03 Numeric sort and selection Input.xml'

Expected stdout:

code:100
read:20

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
 <xsl:for-each select="/tasks/task[@minutes &gt;= 10]">
  <xsl:sort select="@minutes" data-type="number" order="descending"/>
  <xsl:value-of select="@name"/><xsl:text>:</xsl:text>
  <xsl:value-of select="@minutes"/><xsl:text>&#10;</xsl:text>
 </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT 03 Numeric sort and selection Input.xml

<tasks><task name="read" minutes="20"/><task name="rest" minutes="5"/><task name="code" minutes="100"/></tasks>
XSLT 04 - Namespace aware names

The stylesheet prefix d is bound to the source namespace URI. Unprefixed attributes remain unqualified.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT 04 Namespace aware names.xsl' 'XSLT 04 Namespace aware names Input.xml'

Expected stdout:

read

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:d="urn:atlas:tasks" exclude-result-prefixes="d">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
 <xsl:for-each select="/d:tasks/d:task">
  <xsl:value-of select="@name"/><xsl:text>&#10;</xsl:text>
 </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT 04 Namespace aware names Input.xml

<tasks xmlns="urn:atlas:tasks"><task name="read"/></tasks>
XSLT 05 - String parameters

--stringparam binds text. The ampersand remains ordinary data in text output; it is not stylesheet syntax. The installed CLI rejects a value containing both quote styles; that command-argument error is tested separately.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 --stringparam label 'Study & learn' 'XSLT 05 String parameters.xsl' 'XSLT 05 String parameters Input.xml'

Expected stdout:

Study & learn: read

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:param name="label" select="'Task'"/>
<xsl:template match="/">
 <xsl:value-of select="$label"/><xsl:text>: </xsl:text>
 <xsl:value-of select="/task/@name"/><xsl:text>&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT 05 String parameters Input.xml

<task name="read"/>
XSLT 06 - Explicit branches

Attribute values are strings: false is not a boolean literal here. Missing done is not an explicit false.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT 06 Explicit branches.xsl' 'XSLT 06 Explicit branches Input.xml'

Expected stdout:

Pending

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
 <xsl:choose>
  <xsl:when test="not(/tasks/task)"><xsl:text>No tasks</xsl:text></xsl:when>
  <xsl:when test="/tasks/task[@done='false']"><xsl:text>Pending</xsl:text></xsl:when>
  <xsl:otherwise><xsl:text>No explicit pending task</xsl:text></xsl:otherwise>
 </xsl:choose><xsl:text>&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT 06 Explicit branches Input.xml

<tasks><task done="false"/></tasks>
XSLT 07 - Numeric variable

select binds a number. This authored input has valid numeric attributes; the separate contract exercise validates input before summing.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT 07 Numeric variable.xsl' 'XSLT 07 Numeric variable Input.xml'

Expected stdout:

Total: 60; doubled: 120

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:d="urn:atlas:tasks" exclude-result-prefixes="d">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
 <xsl:variable name="total" select="sum(/tasks/task/@minutes)"/>
 <xsl:text>Total: </xsl:text><xsl:value-of select="$total"/>
 <xsl:text>; doubled: </xsl:text><xsl:value-of select="$total * 2"/><xsl:text>&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT 07 Numeric variable Input.xml

<tasks><task minutes="20"/><task minutes="40"/></tasks>
XSLT 08 - Named template and whitespace

normalize-space trims and collapses XML whitespace characters. This does not promise a general Unicode normalization operation.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT 08 Named template and whitespace.xsl' 'XSLT 08 Named template and whitespace Input.xml'

Expected stdout:

Task: read a book

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
 <xsl:call-template name="label">
  <xsl:with-param name="value" select="/task/name"/>
 </xsl:call-template>
</xsl:template>
<xsl:template name="label">
 <xsl:param name="value"/>
 <xsl:text>Task: </xsl:text><xsl:value-of select="normalize-space($value)"/><xsl:text>&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT 08 Named template and whitespace Input.xml

<task><name>  read   a book  </name></task>
XSLT 09 - Copy with one attribute change

The fixed input has no pre-existing state attribute. Tree copying is not byte preservation: serialization escapes the ampersand and can normalize formatting.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT 09 Copy with one attribute change.xsl' 'XSLT 09 Copy with one attribute change Input.xml'

Expected stdout:

<task state="open"><name>A &amp; B</name></task>

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="@*|node()">
 <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>
<xsl:template match="@status">
 <xsl:attribute name="state"><xsl:value-of select="."/></xsl:attribute>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT 09 Copy with one attribute change Input.xml

<task status="open"><name>A &amp; B</name></task>
XSLT exercise A - Validate before summing

Try it first: Accept at most ten tasks with bounded minute attributes, reject malformed values and print one total.

Every selected task must have one to three ASCII digits with numeric value at most 120. Leading zeros are allowed. Other elements/attributes are ignored; this is a projection contract, not full XML schema validation.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT exercise A Validate before summing.xsl' 'XSLT exercise A Validate before summing Input.xml'

Expected stdout:

Total: 60

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
 <xsl:if test="not(/tasks) or count(/tasks/task) &gt; 10">
  <xsl:message terminate="yes">invalid collection</xsl:message>
 </xsl:if>
 <xsl:for-each select="/tasks/task">
  <xsl:if test="string-length(@minutes)=0 or string-length(@minutes)&gt;3 or translate(@minutes,'0123456789','')!='' or number(@minutes)&gt;120">
   <xsl:message terminate="yes">invalid minutes</xsl:message>
  </xsl:if>
 </xsl:for-each>
 <xsl:text>Total: </xsl:text><xsl:value-of select="sum(/tasks/task/@minutes)"/><xsl:text>&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT exercise A Validate before summing Input.xml

<tasks><task minutes="20"/><task minutes="40"/></tasks>
XSLT exercise B - Group with a key

Try it first: Group the flat task records by kind and print each sum once in sorted order.

This fixed flat document has a kind and valid numeric minutes on every task. One representative per key is selected; sorting defines report order. No external document is loaded.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT exercise B Group with a key.xsl' 'XSLT exercise B Group with a key Input.xml'

Expected stdout:

break:5
work:60

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:key name="by-kind" match="task" use="@kind"/>
<xsl:template match="/">
 <xsl:for-each select="/tasks/task[generate-id()=generate-id(key('by-kind',@kind)[1])]">
  <xsl:sort select="@kind"/>
  <xsl:value-of select="@kind"/><xsl:text>:</xsl:text>
  <xsl:value-of select="sum(key('by-kind',@kind)/@minutes)"/><xsl:text>&#10;</xsl:text>
 </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT exercise B Group with a key Input.xml

<tasks><task kind="work" minutes="20"/><task kind="break" minutes="5"/><task kind="work" minutes="40"/></tasks>
XSLT exercise C - Four observable checks

Try it first: Check count, sum, first record name and an upper-bound predicate.

Four predicates are combined into one guard. A failing predicate terminates before the success line. This tests the fixed fixture, not arbitrary XML validity.

Invocation:

XML_CATALOG_FILES= SGML_CATALOG_FILES= /usr/bin/xsltproc --nonet --novalid --nowrite --nomkdir --maxdepth 100 --maxvars 1000 'XSLT exercise C Four observable checks.xsl' 'XSLT exercise C Four observable checks Input.xml'

Expected stdout:

Checks: 4 passed

Test record: passed; libxslt 1.1.35 / libxml2 2.9.13; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
 <xsl:if test="not(count(/tasks/task)=2 and sum(/tasks/task/@minutes)=60 and /tasks/task[1]/@name='read' and not(/tasks/task[@minutes&gt;120]))">
  <xsl:message terminate="yes">test failed</xsl:message>
 </xsl:if>
 <xsl:text>Checks: 4 passed&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Companion: XSLT exercise C Four observable checks Input.xml

<tasks><task name="read" minutes="20"/><task name="code" minutes="40"/></tasks>

Expected program rejections

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: XSLT 01 - Root and value

The stated processor rejected this authored fixture; no successful transformation is claimed. Observed diagnostic category on the stated XSLT 1.0 compiler: Premature end of data.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"><xsl:template match="/">
Expected rejection: XSLT 03 - Numeric sort and selection

The stated processor rejected this authored fixture; no successful transformation is claimed. Observed diagnostic category on the stated XSLT 1.0 compiler: could not compile.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/"><xsl:value-of select="["/></xsl:template>
</xsl:stylesheet>
Expected rejection: XSLT 07 - Numeric variable

The stated processor rejected this authored fixture; no successful transformation is claimed. Observed diagnostic category on the stated XSLT 1.0 compiler: failed to compile.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="["><xsl:text>x</xsl:text></xsl:template>
</xsl:stylesheet>
Expected rejection: XSLT exercise B - Group with a key

The stated processor rejected this authored fixture; no successful transformation is claimed. Observed diagnostic category on the stated XSLT 1.0 compiler: need to specify match or name.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template><xsl:text>x</xsl:text></xsl:template>
</xsl:stylesheet>
Tested learning pack

Tcl Foundations

Tcl programming language: command words and substitution, braced expressions, lists, dictionaries, control flow, procedures, namespaces, explicit file channels and errors. No Tk GUI, Tcl 8.6/9 features or arbitrary script evaluation.

Learners comfortable saving plain text and invoking an installed interpreter. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Use installed /usr/bin/tclsh 8.5.9. This old interpreter is recorded teaching evidence, not a deployment recommendation. The accessible web manual is the later 8.5.19 series; actual 8.5.9 execution bounds the claims. Export one entry and its companions into a fresh toy folder. File example 08 creates only Atlas note.txt with exclusive creation and explicit UTF-8/LF, and refuses to overwrite it; the file remains for inspection. Source in example 09 loads only its authored companion. Data is never eval-ed. Tcl open can launch a pipeline for a leading | path; this pack uses fixed filenames. No sockets, exec, native extensions or downloaded packages. A script interpreter and temporary directory are not an arbitrary-code sandbox. Errors are evaluation outcomes, not a separate compiler pass.

Configuration: Tcl practice instructions.txt
Use a fresh toy directory and the exact command shown for each example.
File example 08 creates Atlas note.txt exclusively and refuses overwrite.
The module example requires its trusted Study helpers.tcl companion.
No Tcl 8.6 try/finally or modern Tcl features are used.

1. Commands receive words

A Tcl command is a sequence of words. Whitespace separates words; braces group a literal word, while double quotes permit substitution. A variable value is substituted as one word; its spaces do not become extra arguments. Braced text still has the special backslash-newline rule.

2. Substitution is not repeated evaluation

Dollar notation reads a variable and square brackets run a command. The result is data at that substitution point, not automatically reparsed as script. list constructs list structure safely. Avoid eval and string-built scripts when ordinary arguments express the operation.

3. Expressions have their own parser

Use expr with a braced expression so the expression engine sees variables directly and can short-circuit. eq compares strings; == can compare numerically. Integer division floors. Leading-zero integer text may be octal in this version; the bounded decimal contract accepts canonical decimal only.

4. Lists and dictionaries preserve structure

Use list, lappend, lindex and llength for lists rather than splitting on spaces. A dictionary maps keys to values; dict exists distinguishes absence from a present empty value. dict incr accumulates integer counts. Sort keys explicitly when output order is a contract.

5. Control flow and procedures

foreach iterates list elements. if, while and for evaluate conditions and bodies; those command arguments have script or expression roles. proc creates local argument variables and returns a value. Default arguments and the final args parameter are different mechanisms.

6. Namespaces organize trusted code

A namespace qualifies command names and variables. source executes a file as code; it is not a data parser. The module example loads only the included fixed companion beside its entry file and calls a qualified procedure. No package discovery or third-party loading is needed.

7. Channels need explicit handling

Open fixed toy paths with a declared access mode. CREAT with EXCL refuses an existing file. Set encoding and newline translation explicitly; close the channel even after an operation fails. Character and byte counts differ; these lessons avoid claiming Unicode grapheme correctness.

8. Observe errors and test boundaries

catch returns a completion code and can capture result and options; nonzero does not always mean an error because return, break and continue also have codes. Return errors with a stable errorcode for contracts. Separate rejected fixtures from successful examples. Tcl 8.5 has no try/finally command.

Quick reference

Assignment

set name value

Store or retrieve a variable.

Literal word

{text with spaces}

Group a word without ordinary substitutions.

Substitution

$name / [command]

Read a variable or substitute a command result.

Expression

expr {$a + $b}

Evaluate fixed arithmetic with braced syntax.

Strings

string length / string equal

Operate on text rather than script source.

List

list / lappend

Build structured elements without manual quoting.

List lookup

lindex / llength

Read an element or count elements.

Dictionary

dict create / dict get

Create and read key-value data.

Presence

dict exists

Distinguish a missing key from its value.

Loop

foreach item $items {...}

Iterate structured list elements.

Procedure

proc name {args} {body}

Define a reusable command with local arguments.

Namespace

namespace eval / name::proc

Organize trusted definitions.

Error

return -code error -errorcode {...}

Return an application error and stable category.

Catch

catch {script} result options

Inspect completion code and details.

File

open path {WRONLY CREAT EXCL}

Create a new file and refuse overwrite.

Channel

fconfigure / close

Set encoding/translation and release the channel.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Tcl 01 - Words and substitution

The substituted name stays one list element. Braces keep dollar and bracket text literal.

Invocation:

/usr/bin/tclsh 'Tcl 01 Words and substitution.tcl'

Expected stdout:

Task: read and code
$name [not executed]
2

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

set name {read and code}
puts "Task: $name"
puts {$name [not executed]}
puts [llength [list $name ready]]
Tcl 02 - Braced expressions

Integer and floating division differ. The substituted text is an operand, not an invoked command.

Invocation:

/usr/bin/tclsh 'Tcl 02 Braced expressions.tcl'

Expected stdout:

60
2
2.5
1

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

set minutes 20
puts [expr {$minutes * 3}]
puts [expr {5 / 2}]
puts [expr {5 / 2.0}]
set text {[not executed]}
puts [expr {$text eq {[not executed]}}]
Tcl 03 - Structured lists

List construction preserves spaces and punctuation. join is display formatting, not reversible serialization.

Invocation:

/usr/bin/tclsh 'Tcl 03 Structured lists.tcl'

Expected stdout:

3
code [small]
read notes | code [small] | rest & reflect

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

set names [list {read notes} {code [small]}]
lappend names {rest & reflect}
puts [llength $names]
puts [lindex $names 1]
puts [join $names { | }]
Tcl 04 - Dictionaries and presence

An existing empty note differs from an absent key. Sorting makes the printed key order explicit.

Invocation:

/usr/bin/tclsh 'Tcl 04 Dictionaries and presence.tcl'

Expected stdout:

25
1
0
minutes,name,note

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

set task [dict create name read minutes 20 note {}]
dict incr task minutes 5
puts [dict get $task minutes]
puts [dict exists $task note]
puts [dict exists $task missing]
puts [join [lsort [dict keys $task]] ,]
Tcl 05 - Iterate and branch

The finite authored list and loop bounds make termination explicit. continue skips only the current iteration.

Invocation:

/usr/bin/tclsh 'Tcl 05 Iterate and branch.tcl'

Expected stdout:

total=60 count=3

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

set total 0
foreach value {0 20 40} {
    if {$value == 0} {continue}
    incr total $value
}
set count 0
while {$count < 3} {incr count}
puts "total=$total count=$count"
Tcl 06 - Procedures and arguments

Procedure arguments are local; the caller name is unchanged. The optional argument has a literal default.

Invocation:

/usr/bin/tclsh 'Tcl 06 Procedures and arguments.tcl'

Expected stdout:

read: 20 minutes
code: 40 minutes
outside

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

proc label {name {minutes 20}} {
    return "$name: $minutes minutes"
}
set name outside
puts [label read]
puts [label code 40]
puts $name
Tcl 07 - Catch a contract error

The contract accepts canonical decimal zero through 120. Leading zeros, signs, whitespace, decimal points and numeric prefixes are intentionally rejected. catch exposes the error without terminating the successful demonstration.

Invocation:

/usr/bin/tclsh 'Tcl 07 Catch a contract error.tcl'

Expected stdout:

code=1 message=invalid minutes
ATLAS MINUTES
120

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

proc minutes {text} {
    if {![regexp {^(0|[1-9][0-9]{0,2})$} $text]} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    if {$text > 120} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    return [expr {$text + 0}]
}
set code [catch {minutes 121} message options]
puts "code=$code message=$message"
puts [dict get $options -errorcode]
puts [minutes 120]
Tcl 08 - Create an exclusive toy file

Run in a new toy folder. Only Atlas note.txt is created and retained. A second run refuses to overwrite the existing file; no cleanup command is part of the example.

Invocation:

/usr/bin/tclsh 'Tcl 08 Create an exclusive toy file.tcl'

Expected stdout:

read and code

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

set out [open {Atlas note.txt} {WRONLY CREAT EXCL}]
set code [catch {
    fconfigure $out -encoding utf-8 -translation lf
    puts $out {read and code}
} message options]
set closed [catch {close $out} closeMessage]
if {$code} {return -options $options $message}
if {$closed} {error $closeMessage}
set input [open {Atlas note.txt} r]
fconfigure $input -encoding utf-8 -translation lf
set text [read $input]
close $input
puts -nonewline $text
Tcl 09 - Load a trusted namespace

source executes the fixed companion as code. file join avoids manually joining path separators; it does not make an arbitrary path trusted.

Invocation:

/usr/bin/tclsh 'Tcl 09 Load a trusted namespace.tcl'

Expected stdout:

40

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Study helpers.tcl}]
puts [study::double 20]

Companion: Study helpers.tcl

namespace eval study {
    proc double {value} {return [expr {$value * 2}]}
}
Tcl exercise A - Validate and total

Try it first: Accept at most ten minutes values from zero through 120; print one total or a diagnostic with status 2.

Each command-line argument is checked before addition. This accepts at most ten canonical decimal values; the empty list totals zero.

Invocation:

/usr/bin/tclsh 'Tcl exercise A Validate and total.tcl' 20 40

Expected stdout:

total=60

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

proc minutes {text} {
    if {![regexp {^(0|[1-9][0-9]{0,2})$} $text]} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    if {$text > 120} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    return [expr {$text + 0}]
}
if {[llength $argv] > 10} {puts stderr {too many values}; exit 2}
set total 0
foreach text $argv {
    if {[catch {minutes $text} value]} {puts stderr $value; exit 2}
    incr total $value
}
puts "total=$total"
Tcl exercise B - Count named items

Try it first: Count repeated labels while preserving spaces, then print sorted counts.

The argument list retains multiword names and dict incr merges duplicates. The output is sorted and deliberately human-readable.

Invocation:

/usr/bin/tclsh 'Tcl exercise B Count named items.tcl' 'read notes' code 'read notes'

Expected stdout:

code: 1
read notes: 2

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

set counts [dict create]
foreach name $argv {dict incr counts $name}
foreach name [lsort [dict keys $counts]] {
    puts "$name: [dict get $counts $name]"
}
Tcl exercise C - Four observable cases

Try it first: Test zero, the upper bound, an out-of-range value and ambiguous leading-zero text.

The four cases assert both completion code and value. An assertion failure raises an error rather than printing a success count.

Invocation:

/usr/bin/tclsh 'Tcl exercise C Four observable cases.tcl'

Expected stdout:

4 checks passed

Test record: passed; Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

proc minutes {text} {
    if {![regexp {^(0|[1-9][0-9]{0,2})$} $text]} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    if {$text > 120} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    return [expr {$text + 0}]
}
set passed 0
foreach {input expectedCode expectedValue} {0 0 0 120 0 120 121 1 {invalid minutes} 08 1 {invalid minutes}} {
    set code [catch {minutes $input} value]
    if {$code != $expectedCode || $value ne $expectedValue} {error {test failed}}
    incr passed
}
puts "$passed checks passed"

Expected evaluation failures

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: Tcl 01 - Words and substitution

This authored fixture was evaluated and failed as expected. It is not a static compiler rejection or a successful program. Observed diagnostic category on the stated interpreter: missing close-brace.

set value {unfinished
Expected rejection: Tcl 02 - Braced expressions

This authored fixture was evaluated and failed as expected. It is not a static compiler rejection or a successful program. Observed diagnostic category on the stated interpreter: missing operand.

expr {1 +}
Expected rejection: Tcl 04 - Dictionaries and presence

This authored fixture was evaluated and failed as expected. It is not a static compiler rejection or a successful program. Observed diagnostic category on the stated interpreter: not known in dictionary.

dict get {name read} absent
Expected rejection: Tcl 06 - Procedures and arguments

This authored fixture was evaluated and failed as expected. It is not a static compiler rejection or a successful program. Observed diagnostic category on the stated interpreter: wrong # args.

proc pair {a b} {return $a}
pair one
Tested learning pack

Expect Foundations

Expect is a Tcl extension for scripted conversations with processes, not a second general-purpose language or a shell. This pack covers fixed toy children, literal/regular-expression matching, send, timeout, EOF, wait status, buffering and bounded conversation states. It does not automate real services.

Learners comfortable saving plain text and invoking an installed interpreter. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

Use /usr/bin/expect -N -n with installed Expect 5.45 and embedded Tcl 8.5.9. These old installed versions are limited teaching evidence. -N and -n suppress system and user Expect startup files. Export Expect support.tcl, one entry .exp and its unique child companion into the same new toy directory. Each entry spawns only /usr/bin/tclsh with that authored child; no shell, sign-ins, network, secrets or external applications. Child transcripts are ASCII and use the tested local pseudo-terminal CRLF convention. stty_init changes only each newly spawned pseudo-terminal. log_user 0 suppresses transcript echo but is not a security boundary. Explicit timeouts, EOF and wait are distinct; a timeout never proves child exit. The harness retains native child handles and complete blocking wait receipts. Cooperative cleanup closes those channels and waits; it requires event-loop progress. An outer timeout collects only the direct controller and reports unresolved child cleanup as uncertain. Examples and support code are trusted; this is not an arbitrary-process sandbox.

Configuration: Expect support.tcl
# Trusted fixed fixtures only; no arbitrary command argument.
set timeout 3
set stty_init {-echo}
log_user 0
proc startToy {file args} {
    global spawn_id
    spawn -noecho /usr/bin/tclsh $file {*}$args
    match_max -i $spawn_id 4096
    return $spawn_id
}
proc exact {id text} {
    expect {
        -i $id
        -exact $text {return}
        eof {error {unexpected EOF}}
        timeout {error {reply timeout}}
    }
}
proc finish {id expected} {
    expect {
        -i $id
        eof {}
        timeout {error {EOF timeout}}
    }
    set result [wait -i $id]
    if {[llength $result] != 4 || [lindex $result 2] != 0 || [lindex $result 3] != $expected} {
        error {unexpected child status}
    }
}

1. A Tcl extension with a process role

Expect adds spawn, send and expect to Tcl. A spawn id identifies a conversation channel; it is not the child process ID. This pack spawns only its authored local Tcl fixtures using separate arguments, never a shell command string.

2. Prompt bytes and flushing matter

An interactive prompt may have no trailing newline, so the toy child explicitly flushes it. A pseudo-terminal can transform LF to CRLF and echo typed text. The support file disables echo for newly spawned children; matching and output assumptions remain platform-specific.

3. Match the intended pattern mode

Use -exact when punctuation is literal. Default patterns are globs; -re selects regular expressions. Match only the required bounded protocol, and capture needed expect_out values before the next match overwrites them. Matching a substring alone is not full-message validation. Keep the shown multiline clause form: Tcl quoting and Expect pattern-list parsing are separate layers.

4. Send data as one argument

send -- ends option parsing and sends one data value. Tcl substitution does not automatically reparse that value as code. The fixture reads a line as data; arbitrary child programs could interpret it differently. Reject protocol line breaks and excessive length before sending.

5. Timeout EOF and status are distinct

timeout means a match did not arrive in time; eof means the channel ended. Neither proves a successful child result. wait reaps the child and returns operating-system and child-status fields, with possible extra signal fields. Check those fields instead of assuming EOF is success.

6. Progress is a state transition

exp_continue continues the same matching command. Its default restarts the timeout; -continue_timer keeps the original deadline. Count or bound progress messages. For deterministic timeout practice, a zero-time poll occurs after READY while the toy waits for an explicit quit message.

7. Keep the scope explicit

Use -i with a saved spawn id in helper procedures. Only one authored child is active at a time here. No attach, interact, background monitoring, broad kill, secret logging or real application control is included. close affects a channel; wait concerns process lifetime.

8. Test conversations rather than happy paths

Test normal replies, malformed reply text, early EOF, expected child failure and timeout separately. The toy child failures are controlled evidence, not successful commands. Shared support code checks EOF and exact exit status, while the harness checks retained files, complete native child wait receipts and direct controller collection.

Quick reference

Start

spawn -noecho /usr/bin/tclsh file

Create a channel for the fixed local child.

Channel

spawn_id

Save the identifier used with -i.

Literal

expect -exact text

Match punctuation literally.

Regular expression

expect -re {pattern}

Use a fixed regular expression.

Capture

expect_out(1,string)

Read a captured subgroup immediately.

Transmit

send -i $id -- $text

Send data to the chosen child channel.

Timeout

set timeout 3

Set a bounded match wait in seconds.

Poll

expect -timeout 0

Check immediately without a positive wait.

End

eof

Handle channel closure explicitly.

Reap

wait -i $id

Collect OS and child exit information.

Continuation

exp_continue -continue_timer

Continue without restarting the match timer.

Echo

set stty_init {-echo}

Configure newly spawned pseudo-terminals only.

Display

log_user 0

Suppress ordinary child transcript echo.

Buffer

match_max -i $id 4096

Set the matching buffer; not a hostile-input sandbox.

Startup

expect -N -n file

Suppress system and user startup scripts.

Flush

flush stdout

Make a non-newline child prompt observable.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Expect 01 - Spawn match and reap

The channel match and the child exit status are both checked. These calls pass this pack's fixed authored child paths. The helper has no arbitrary-path allowlist or sandbox guarantee.

Invocation:

/usr/bin/expect -N -n 'Expect 01 Spawn match and reap.exp'

Expected stdout:

ready; child status 0

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect 01 Spawn match and reap Child.tcl}]
set id [startToy $child]
exact $id "READY\r\n"
finish $id 0
puts {ready; child status 0}

Companion: Expect 01 Spawn match and reap Child.tcl

fconfigure stdout -translation lf -buffering none
puts READY
Expect 02 - Prompt and response

The child flushes a prompt without a newline. The sent carriage return completes the pseudo-terminal line; the fixture treats the response as text.

Invocation:

/usr/bin/expect -N -n 'Expect 02 Prompt and response.exp'

Expected stdout:

greeting checked

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect 02 Prompt and response Child.tcl}]
set id [startToy $child]
exact $id {Name? }
send -i $id -- "read\r"
exact $id "Hello read\r\n"
finish $id 0
puts {greeting checked}

Companion: Expect 02 Prompt and response Child.tcl

fconfigure stdout -translation lf -buffering none
puts -nonewline {Name? }
flush stdout
if {[gets stdin name] < 0} {exit 3}
puts "Hello $name"
Expect 03 - Literal punctuation

-exact keeps brackets, star and question mark literal. Tcl quoting is a separate layer from Expect pattern mode.

Invocation:

/usr/bin/expect -N -n 'Expect 03 Literal punctuation.exp'

Expected stdout:

literal matched

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect 03 Literal punctuation Child.tcl}]
set id [startToy $child]
exact $id "\[ready\]*?\r\n"
finish $id 0
puts {literal matched}

Companion: Expect 03 Literal punctuation Child.tcl

fconfigure stdout -translation lf -buffering none
puts {[ready]*?}
Expect 04 - Capture a bounded count

Copy the capture before another expect call. The fixed reply supplies canonical digits; a match alone is not a complete untrusted-message validator.

Invocation:

/usr/bin/expect -N -n 'Expect 04 Capture a bounded count.exp'

Expected stdout:

count=20

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect 04 Capture a bounded count Child.tcl}]
set id [startToy $child]
expect {
        -i $id
    -re {COUNT ([0-9]{1,3})\r\n} {set count $expect_out(1,string)}
    eof {error {missing count}}
    timeout {error {count timeout}}
}
finish $id 0
puts "count=$count"

Companion: Expect 04 Capture a bounded count Child.tcl

fconfigure stdout -translation lf -buffering none
puts {COUNT 20}
Expect 05 - Alternative replies

The controller handles both known outcomes and verifies the corresponding child status. A handled child status 7 is still a child failure, even though this observation script exits zero.

Invocation:

/usr/bin/expect -N -n 'Expect 05 Alternative replies.exp' ok

Expected stdout:

reply=ok child=0

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect 05 Alternative replies Child.tcl}]
set mode [lindex $argv 0]
if {$mode ni {ok error}} {puts stderr {invalid mode}; exit 2}
set id [startToy $child $mode]
expect {
        -i $id
    -exact "OK\r\n" {set reply ok; set status 0}
    -exact "ERROR\r\n" {set reply rejected; set status 7}
    eof {error {missing reply}}
    timeout {error {reply timeout}}
}
finish $id $status
puts "reply=$reply child=$status"

Companion: Expect 05 Alternative replies Child.tcl

fconfigure stdout -translation lf -buffering none
if {[lindex $argv 0] eq {error}} {puts ERROR; exit 7}
puts OK
Expect 06 - Deterministic timeout branch

After READY the child waits for quit and emits no further text. The zero-time poll takes the timeout branch deterministically; this does not test elapsed-time accuracy or positive-time deadlines.

Invocation:

/usr/bin/expect -N -n 'Expect 06 Deterministic timeout branch.exp'

Expected stdout:

timeout observed=1; child reaped

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect 06 Deterministic timeout branch Child.tcl}]
set id [startToy $child]
exact $id "READY\r\n"
set observed 0
set timeout 0
expect {
    -i $id
    -exact NEVER {error {unexpected reply}}
    timeout {set observed 1}
    eof {error {early EOF}}
}
set timeout 3
send -i $id -- "quit\r"
finish $id 0
puts "timeout observed=$observed; child reaped"

Companion: Expect 06 Deterministic timeout branch Child.tcl

fconfigure stdout -translation lf -buffering none
puts READY
flush stdout
if {[gets stdin line] < 0 || $line ne {quit}} {exit 4}
Expect 07 - EOF is not success

This deliberately failing child produces no text. The controller succeeds only because it observes the specified failure; EOF alone would miss the nonzero status.

Invocation:

/usr/bin/expect -N -n 'Expect 07 EOF is not success.exp'

Expected stdout:

EOF observed=1; child status 7

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect 07 EOF is not success Child.tcl}]
set id [startToy $child]
expect {
        -i $id
    eof {set ended 1}
    timeout {error {EOF timeout}}
}
set result [wait -i $id]
if {[llength $result] != 4 || [lindex $result 2] != 0 || [lindex $result 3] != 7} {error {wrong status}}
puts "EOF observed=$ended; child status 7"

Companion: Expect 07 EOF is not success Child.tcl

fconfigure stdout -translation lf -buffering none
exit 7
Expect 08 - Progress with one deadline

exp_continue retains one matching context; -continue_timer avoids extending the original deadline. The toy also bounds the count. This count check does not enforce unique step numbers.

Invocation:

/usr/bin/expect -N -n 'Expect 08 Progress with one deadline.exp'

Expected stdout:

2 progress messages checked

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect 08 Progress with one deadline Child.tcl}]
set id [startToy $child]
set count 0
expect {
        -i $id
    -re {STEP [12]\r\n} {
        incr count
        if {$count > 2} {error {too many steps}}
        exp_continue -continue_timer
    }
    -exact "DONE\r\n" {}
    eof {error {missing DONE}}
    timeout {error {progress timeout}}
}
finish $id 0
if {$count != 2} {error {missing step}}
puts {2 progress messages checked}

Companion: Expect 08 Progress with one deadline Child.tcl

fconfigure stdout -translation lf -buffering none
puts {STEP 1}
puts {STEP 2}
puts DONE
Expect 09 - Pass punctuation as data

The child echoes the value as text, and -exact compares it literally. The accepted line contract is short authored ASCII without CR/LF; terminal controls and arbitrary Unicode are outside the demonstration.

Invocation:

/usr/bin/expect -N -n 'Expect 09 Pass punctuation as data.exp' '[word]; $x *?'

Expected stdout:

data round trip checked

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect 09 Pass punctuation as data Child.tcl}]
set text [lindex $argv 0]
if {[string length $text] > 40 || ![regexp {^[ -~]*$} $text]} {puts stderr {invalid line}; exit 2}
set id [startToy $child]
exact $id {Text? }
send -i $id -- "$text\r"
exact $id "ECHO $text\r\n"
finish $id 0
puts {data round trip checked}

Companion: Expect 09 Pass punctuation as data Child.tcl

fconfigure stdout -translation lf -buffering none
puts -nonewline {Text? }
flush stdout
if {[gets stdin value] < 0} {exit 3}
puts "ECHO $value"
Expect exercise A - Validate a reply

Try it first: Check a fixed TOTAL reply and reject malformed text while collecting the child status.

The malformed reply reaches EOF without satisfying the expected pattern. The child is reaped on both paths; an invalid reply returns controller status 2. This is a fixed single-message fixture, not a general streaming parser.

Invocation:

/usr/bin/expect -N -n 'Expect exercise A Validate a reply.exp' good

Expected stdout:

total 60 verified

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect exercise A Validate a reply Child.tcl}]
set mode [lindex $argv 0]
if {$mode ni {good bad}} {puts stderr {invalid mode}; exit 2}
set id [startToy $child $mode]
set valid 0
expect {
        -i $id
    -re {^TOTAL ([0-9]{1,3})\r\n} {set valid [expr {$expect_out(1,string) eq {60}}]}
    eof {set ended 1}
    timeout {error {total timeout}}
}
if {![info exists ended]} {finish $id 0} else {
    set result [wait -i $id]
    if {[llength $result] != 4 || [lindex $result 2] != 0 || [lindex $result 3] != 0} {error {child failure}}
}
if {!$valid} {puts stderr {invalid total reply}; exit 2}
puts {total 60 verified}

Companion: Expect exercise A Validate a reply Child.tcl

fconfigure stdout -translation lf -buffering none
if {[lindex $argv 0] eq {bad}} {puts {TOTAL nope}} else {puts {TOTAL 60}}
Expect exercise B - Two conversation states

Try it first: Complete two prompt-response states and verify one final summary.

The controller advances only after the expected prompt. The next input is not sent early. Both values are fixed data and no real application is involved.

Invocation:

/usr/bin/expect -N -n 'Expect exercise B Two conversation states.exp'

Expected stdout:

two states checked

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect exercise B Two conversation states Child.tcl}]
set id [startToy $child]
exact $id {First? }
send -i $id -- "read\r"
exact $id {Second? }
send -i $id -- "code\r"
exact $id "PLAN read + code\r\n"
finish $id 0
puts {two states checked}

Companion: Expect exercise B Two conversation states Child.tcl

fconfigure stdout -translation lf -buffering none
puts -nonewline {First? }
flush stdout
if {[gets stdin first] < 0} {exit 3}
puts -nonewline {Second? }
flush stdout
if {[gets stdin second] < 0} {exit 3}
puts "PLAN $first + $second"
Expect exercise C - Four child cases

Try it first: Check four authored child modes and verify each output and exit status.

Four children are started and reaped sequentially, including one expected status 7. No parallel or unrelated process is controlled. These are four child cases within one accepted controller example.

Invocation:

/usr/bin/expect -N -n 'Expect exercise C Four child cases.exp'

Expected stdout:

4 child cases checked

Test record: passed; Expect 5.45 with Tcl 8.5.9; macOS 27.0.1 arm64; 2026-10-26. macOS 27.0.1 (arm64); Darwin 27.0.0

source [file join [file dirname [info script]] {Expect support.tcl}]
set child [file join [file dirname [info script]] {Expect exercise C Four child cases Child.tcl}]
set passed 0
foreach {mode expectedStatus expectedText} {zero 0 ZERO upper 0 UPPER reject 7 REJECT empty 0 EMPTY} {
    set id [startToy $child $mode]
    exact $id "$expectedText\r\n"
    finish $id $expectedStatus
    incr passed
}
puts "$passed child cases checked"

Companion: Expect exercise C Four child cases Child.tcl

fconfigure stdout -translation lf -buffering none
switch -- [lindex $argv 0] {
    zero {puts ZERO}
    upper {puts UPPER}
    reject {puts REJECT; exit 7}
    empty {puts EMPTY}
    default {exit 9}
}

Expected evaluation failures

These invalid fixtures test diagnostic behavior. They are separate from the successful runtime examples and are not counted as accepted programs.

Expected rejection: Expect 01 - Spawn match and reap

This authored fixture was evaluated and failed as expected. It is not a static compiler rejection or a successful program. Observed diagnostic category on the stated interpreter: missing close-brace.

set x {unfinished
Expected rejection: Expect 03 - Literal punctuation

This authored fixture was evaluated and failed as expected. It is not a static compiler rejection or a successful program. Observed diagnostic category on the stated interpreter: bad flag.

expect -notAnOption value
Expected rejection: Expect 04 - Capture a bounded count

This authored fixture was evaluated and failed as expected. It is not a static compiler rejection or a successful program. Observed diagnostic category on the stated interpreter: couldn't compile regular expression pattern.

regexp {[} text
Expected rejection: Expect 09 - Pass punctuation as data

This authored fixture was evaluated and failed as expected. It is not a static compiler rejection or a successful program. Observed diagnostic category on the stated interpreter: intentional fixture failure.

error {intentional fixture failure}
Tested learning pack

Objective-C Foundations

Objects and messages, properties, Foundation values, UTF-16, protocols, categories, blocks, ARC relationships, recoverable errors, a tiny local file and separate source files. Introductory macOS-only scope.

Learners familiar with the C Foundations pack and basic terminal use. Allow 4 to 6 hours.

Pack status: tested. Test details apply only to the included examples. Full language or format coverage remains future work.

Runtime and practice instructions

In a new owned practice directory, compile an exported example with /usr/bin/clang -x objective-c -std=c17 -fobjc-arc -fno-modules -Wall -Wextra -Werror "Example.m" -framework Foundation -o "Practice", then run ./Practice. Replace Example.m with the exact filename. For Objective-C 09 Main.m, also pass "Atlas minutes.m" and save "Atlas minutes.h" beside both files. The file example creates and retains Atlas practice note.txt; a second run intentionally refuses it. Use only the installed Apple toolchain with macOS Foundation. Compilation uses SDK 27.0 headers; execution uses system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. No iOS, GNUstep, other OS, Objective-C++, UI, concurrency or package-manager support is tested. The offline browser exports text and never compiles or executes these programs.

Configuration: Objective-C run instructions.txt
In a new owned practice directory, compile an exported example with /usr/bin/clang -x objective-c -std=c17 -fobjc-arc -fno-modules -Wall -Wextra -Werror "Example.m" -framework Foundation -o "Practice", then run ./Practice. Replace Example.m with the exact filename. For Objective-C 09 Main.m, also pass "Atlas minutes.m" and save "Atlas minutes.h" beside both files. The file example creates and retains Atlas practice note.txt; a second run intentionally refuses it. Use only the installed Apple toolchain with macOS Foundation. Compilation uses SDK 27.0 headers; execution uses system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. No iOS, GNUstep, other OS, Objective-C++, UI, concurrency or package-manager support is tested. The offline browser exports text and never compiles or executes these programs.

1. Build and run distinct stages

A .m source is compiled as Objective-C and linked with Foundation. This pack pins Apple Clang, ARC and a C17 base mode; C17 is not an Objective-C standard edition. Compiler acceptance does not prove correct behavior. Expected rejected fixtures are recorded separately and are never executed. The exported examples are trusted authored source, not a sandbox for arbitrary code.

2. Objects, messages and initialization

A class describes an interface and implementation. + marks class methods; - marks instance methods. Selector components and parameter order form the message name. Properties usually synthesize accessor methods and storage. An initializer calls its superclass and may return nil. Validate inputs before establishing invariants, and distinguish a nil Objective-C receiver from an invalid C pointer.

3. Strings, values and collections

Foundation provides NSString, NSNumber, NSArray and NSDictionary; these are framework types, not a second language. NSString length and NSRange offsets use UTF-16 units. Composed-sequence enumeration is different from counting bytes. Check NSNotFound and collection bounds. nil means absence; NSNull is an object representing explicit null. Sort dictionary keys when output order matters.

4. Copying and ownership

A strong relationship owns an object; weak observes without keeping it alive and becomes nil when the supported object is deallocated. A copy property invokes copying on assignment, which need not allocate a distinct object or deep-copy an object graph. ARC inserts ownership operations; cycles can still leak. Autorelease pools bound pending autoreleases and are not garbage collectors. nonatomic properties do not make concurrent mutation safe.

5. Protocols, categories and blocks

Protocols declare method contracts; adopting classes must supply required behavior. Class extensions can declare implementation details. Categories add methods but must avoid name collisions; this pack adds a prefixed method only to its own class. Blocks capture state. A block owned by an object can create a cycle if it strongly captures that object; the synchronous example uses a weak capture and a temporary strong local.

6. Errors and dynamic boundaries

Follow each API return-value contract before reading NSError. NSError outputs need not be cleared on success. Cocoa conventions treat exceptions as programming errors, not the ordinary invalid-input path. A JSON parser returns Foundation objects: validate their classes, required fields and application bounds separately. Lightweight generics and nullability annotations are compiler aids, not runtime schema validators.

7. Local files and source organization

Use a new owned practice directory. The file example retains a tiny UTF-8 file, refuses an existing path and requests a no-overwrite write. It is not a defense against an attacker controlling the directory. Export the local header and implementation beside the multi-file main, then compile both .m files. No module, package manager, GUI framework or network operation is needed.

8. What the evidence means

Normal compilation, execution output, boundary checks and expected compiler rejections are different evidence categories. These tests cover fixed inputs on one macOS arm64 compiler/SDK. They do not establish whole-language mastery, cross-platform compatibility, performance, arbitrary-code isolation or absence of every memory defect. Browser, PDF, accessibility and final Library release checks remain separate gates.

Quick reference

Source

.m / clang -x objective-c

Objective-C source mode; compile and link before running.

Ownership mode

-fobjc-arc

Enable automatic reference counting for Objective-C objects.

Classes

@interface / @implementation

Declare the interface and implement methods.

Messages

[receiver method:argument]

Send a selector with ordered arguments.

Methods

+ / -

Class versus instance methods.

Initialization

instancetype / init / nil

Initialize via the superclass; handle a nullable result.

Properties

nonatomic, copy / strong / weak

Choose semantics; nonatomic provides no synchronization.

Literals

@"text" / @20 / @[] / @{}

Create object strings, boxed numbers and collections.

Absence

nil / [NSNull null]

No object versus an explicit null object.

Text units

length / NSRange / NSNotFound

UTF-16 offsets and a checked failed-search marker.

Protocols

@protocol / id<Protocol>

A declared method contract; implement required behavior.

Categories

@interface Class (Category)

Add distinctly named methods; do not replace existing behavior.

Blocks

^{ ... } / __block

Capture behavior and explicitly mutable captured bindings.

Pools

@autoreleasepool

Bound pending autoreleases in this command-line program.

Errors

NSError ** / nullable result

Inspect the result before consulting the error output.

Boundary checks

isKindOfClass: / length limits

Validate dynamic values and application constraints explicitly.

Examples and exercises

Examples are shown as text. Export files and use the stated runtime or interpreter separately to practice. Module and multi-file examples require their companion files. C and C++ examples need the named compiler and standard mode. TypeScript also needs its exported configuration files and separate static checking before JavaScript execution. SQL files use the SQLite CLI with a fresh :memory: database; shell files name their interpreter and may retain new toy folders for inspection. Try exercises A, B and C before expanding their solutions.

Objective-C 01 - Objects and messages

The + method receives a class message; the - method receives an instance message. messageFor: requires a non-nil string. Messaging nil for this integer-valued length returns zero; passing a null C pointer to puts would not be safe. The print calls use only known non-nil UTF-8 strings.

Expected stdout:

Objective-C
Hello, Ada
Nil length: 0

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
@interface AtlasGreeting : NSObject
+ (NSString *)topic;
- (NSString *)messageFor:(NSString *)name;
@end
@implementation AtlasGreeting
+ (NSString *)topic { return @"Objective-C"; }
- (NSString *)messageFor:(NSString *)name {
    return [@"Hello, " stringByAppendingString:name];
}
@end
int main(void) {
    @autoreleasepool {
        AtlasGreeting *greeting = [AtlasGreeting new];
        puts([[AtlasGreeting topic] UTF8String]);
        puts([[greeting messageFor:@"Ada"] UTF8String]);
        NSString *absent = nil;
        printf("Nil length: %lu\n", (unsigned long)[absent length]);
    }
    return 0;
}
Objective-C 02 - Properties and copying

The synthesized copy setter stores a string copy; strong stores an owning reference to the same mutable object. copy does not promise a new address or a deep copy of arbitrary graphs. nonatomic does not provide synchronization. This single-threaded fixture initializes both properties before use.

Expected stdout:

Read
Read more
Same reference: yes

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
@interface AtlasNote : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, strong) NSMutableString *shared;
@end
@implementation AtlasNote
@end
int main(void) {
    @autoreleasepool {
        NSMutableString *draft = [NSMutableString stringWithString:@"Read"];
        AtlasNote *note = [AtlasNote new];
        note.title = draft;
        note.shared = draft;
        [draft appendString:@" more"];
        puts([note.title UTF8String]);
        puts([note.shared UTF8String]);
        printf("Same reference: %s\n", note.shared == draft ? "yes" : "no");
    }
    return 0;
}
Objective-C 03 - UTF-16 and composed sequences

NSString length and NSRange offsets count UTF-16 code units, not bytes or displayed characters. Composed-sequence enumeration groups this authored combining accent with its letter. Segmentation can depend on the OS Unicode implementation; this fixture does not establish every script or emoji rule. Check NSNotFound before using a search range.

Expected stdout:

UTF-16 units: 5
UTF-8 bytes: 6
Composed sequences: 4
Search: absent

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
int main(void) {
    @autoreleasepool {
        NSString *text = @"Cafe\u0301";
        __block NSUInteger sequences = 0;
        [text enumerateSubstringsInRange:NSMakeRange(0, text.length)
            options:NSStringEnumerationByComposedCharacterSequences
            usingBlock:^(NSString *substring, NSRange range, NSRange enclosing, BOOL *stop) {
                (void)substring; (void)range; (void)enclosing; (void)stop;
                sequences += 1;
            }];
        printf("UTF-16 units: %lu\n", (unsigned long)text.length);
        printf("UTF-8 bytes: %lu\n", (unsigned long)[text lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
        printf("Composed sequences: %lu\n", (unsigned long)sequences);
        NSRange missing = [text rangeOfString:@"z"];
        puts(missing.location == NSNotFound ? "Search: absent" : "Search: found");
    }
    return 0;
}
Objective-C 04 - Collections and absence

Collections hold objects: NSNumber boxes these small integers and NSNull represents explicit null. nil is absence, not a collection element. Dictionary iteration has no report-order guarantee, so sort the ASCII keys. Lightweight generics aid compile-time checks; validate types at dynamic boundaries. The sum is safe only for these bounded authored values.

Expected stdout:

Total: 60
code: 40
read: 20
Explicit null: yes
Missing: yes
First: absent

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
int main(void) {
    @autoreleasepool {
        NSArray<NSNumber *> *minutes = @[@10, @20, @30];
        NSInteger total = 0;
        for (NSNumber *value in minutes) { total += value.integerValue; }
        printf("Total: %ld\n", (long)total);
        NSDictionary<NSString *, NSNumber *> *totals = @{@"read": @20, @"code": @40};
        for (NSString *key in [[totals allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
            printf("%s: %ld\n", [key UTF8String], (long)[totals[key] integerValue]);
        }
        NSDictionary<NSString *, id> *row = @{@"note": [NSNull null]};
        printf("Explicit null: %s\n", row[@"note"] == [NSNull null] ? "yes" : "no");
        printf("Missing: %s\n", row[@"missing"] == nil ? "yes" : "no");
        NSArray *empty = @[];
        puts(empty.firstObject == nil ? "First: absent" : "First: present");
    }
    return 0;
}
Objective-C 05 - A protocol and a category

The protocol specifies a method contract; the class supplies the implementation. A class extension declares an implementation detail, not a security boundary. The category adds a prefixed method on this authored class. It adds no stored property and replaces no existing method. This initializer assumes its authored minutes input is valid; exercise A adds validation.

Expected stdout:

25 minutes
Session: 25 minutes

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
@protocol AtlasDescribing <NSObject>
- (NSString *)summary;
@end
@interface AtlasSession : NSObject <AtlasDescribing>
- (instancetype)initWithMinutes:(NSInteger)minutes;
@end
@interface AtlasSession ()
@property (nonatomic) NSInteger minutes;
@end
@implementation AtlasSession
- (instancetype)initWithMinutes:(NSInteger)minutes {
    self = [super init];
    if (self) { _minutes = minutes; }
    return self;
}
- (NSString *)summary {
    return [NSString stringWithFormat:@"%ld minutes", (long)self.minutes];
}
@end
@interface AtlasSession (AtlasLabel)
- (NSString *)atlas_label;
@end
@implementation AtlasSession (AtlasLabel)
- (NSString *)atlas_label { return [@"Session: " stringByAppendingString:[self summary]]; }
@end
int main(void) {
    @autoreleasepool {
        AtlasSession *session = [[AtlasSession alloc] initWithMinutes:25];
        id<AtlasDescribing> view = session;
        puts([[view summary] UTF8String]);
        puts([[session atlas_label] UTF8String]);
    }
    return 0;
}
Objective-C 06 - Weak ownership and a block

The counter owns its copied block, but that block captures only a weak reference back. A temporary strong local keeps the object alive during the synchronous call if it still exists. After the last owner and the inner pool are gone, the observer is nil. No intentional leaking cycle, asynchronous timing or manual release is demonstrated. ARC manages ownership; it is not a general leak or thread-safety guarantee.

Expected stdout:

Value: 2
Owner released: yes

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
@interface AtlasCounter : NSObject
@property (nonatomic) NSInteger value;
@property (nonatomic, copy) void (^tick)(void);
@end
@implementation AtlasCounter
@end
int main(void) {
    @autoreleasepool {
        __weak AtlasCounter *observer = nil;
        @autoreleasepool {
            AtlasCounter *counter = [AtlasCounter new];
            observer = counter;
            __weak AtlasCounter *weakCounter = counter;
            counter.tick = ^{
                AtlasCounter *current = weakCounter;
                if (current != nil) { current.value += 1; }
            };
            counter.tick();
            counter.tick();
            printf("Value: %ld\n", (long)counter.value);
            counter = nil;
        }
        printf("Owner released: %s\n", observer == nil ? "yes" : "no");
    }
    return 0;
}
Objective-C 07 - Parsing is not validation

A successful parse produces Foundation values, not a validated record. This wrapper accepts at most 1024 bytes, a dictionary root and a title of 1 to 40 UTF-16 units. It allows extra keys and does not enforce a general JSON schema or detect duplicate keys. Check the returned title first; the NSError output is only meaningful on failure and is not cleared on success. Nullability annotations document intent but do not perform runtime checks.

Expected stdout:

Title: Read
Rejected with NSError
Rejected with NSError

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
NS_ASSUME_NONNULL_BEGIN
static NSString * _Nullable AtlasTitleFromData(NSData * _Nullable data,
    NSError * _Nullable __autoreleasing * _Nullable error) {
    if (data == nil || data.length > 1024) {
        if (error != NULL) { *error = [NSError errorWithDomain:@"AtlasInput" code:1 userInfo:nil]; }
        return nil;
    }
    NSError *parseError = nil;
    id root = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    if (root == nil) {
        if (error != NULL) { *error = parseError; }
        return nil;
    }
    if (![root isKindOfClass:[NSDictionary class]]) {
        if (error != NULL) { *error = [NSError errorWithDomain:@"AtlasInput" code:2 userInfo:nil]; }
        return nil;
    }
    id title = [(NSDictionary *)root objectForKey:@"title"];
    if (![title isKindOfClass:[NSString class]] || [title length] == 0 || [title length] > 40) {
        if (error != NULL) { *error = [NSError errorWithDomain:@"AtlasInput" code:3 userInfo:nil]; }
        return nil;
    }
    return title;
}
NS_ASSUME_NONNULL_END
int main(void) {
    @autoreleasepool {
        for (NSString *text in @[@"{\"title\":\"Read\"}", @"{", @"[]"]) {
            NSError *error = nil;
            NSString *title = AtlasTitleFromData([text dataUsingEncoding:NSUTF8StringEncoding], &error);
            if (title != nil) { printf("Title: %s\n", [title UTF8String]); }
            else if (error != nil) { puts("Rejected with NSError"); }
            else { return 2; }
        }
    }
    return 0;
}
Objective-C 08 - A local UTF-8 round trip

Run only in a new owned practice directory. The fixed filename is retained, never removed by the program; a second run intentionally refuses it. The no-overwrite write option protects against an intervening existing file, but this is not a hostile-filesystem sandbox. The example performs explicit UTF-8 decoding and checks each API failure return. Disk-full and permission failures are handled but are not injected by the harness.

Expected stdout:

Round trip: equal

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
int main(void) {
    @autoreleasepool {
        NSString *path = @"Atlas practice note.txt";
        NSFileManager *files = [NSFileManager defaultManager];
        if ([files fileExistsAtPath:path]) {
            fputs("Refusing an existing practice file\n", stderr);
            return 3;
        }
        NSError *error = nil;
        NSData *bytes = [@"Read for 20 minutes\n" dataUsingEncoding:NSUTF8StringEncoding];
        if (![bytes writeToFile:path options:NSDataWritingWithoutOverwriting error:&error]) {
            fputs("Write failed\n", stderr);
            return 4;
        }
        NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
        if (text == nil) { fputs("Read failed\n", stderr); return 5; }
        puts([text isEqualToString:@"Read for 20 minutes\n"] ? "Round trip: equal" : "Round trip: different");
    }
    return 0;
}
Objective-C 09 - A local header and implementation

Export all three files and compile both .m files together. The header declares a nullable result; the implementation accepts only 0 through 120. This is a C-linkage function using Objective-C objects in one linked executable, not a module, framework or package.

Expected stdout:

Companion: 40

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import "Atlas minutes.h"
#include <stdio.h>
int main(void) {
    @autoreleasepool {
        NSNumber *result = AtlasDoubleMinutes(20);
        if (result == nil) { return 2; }
        printf("Companion: %ld\n", (long)result.integerValue);
    }
    return 0;
}

Companion: Atlas minutes.h

#ifndef ATLAS_MINUTES_H
#define ATLAS_MINUTES_H
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
NSNumber * _Nullable AtlasDoubleMinutes(NSInteger value);
NS_ASSUME_NONNULL_END
#endif

Companion: Atlas minutes.m

#import "Atlas minutes.h"
NSNumber *AtlasDoubleMinutes(NSInteger value) {
    if (value < 0 || value > 120) { return nil; }
    return @(value * 2);
}
Objective-C exercise A - A validated initializer

Try it first: Build a record with a copied nonempty title of at most 40 UTF-16 units and minutes in 0 through 120. Reject invalid initialization with nil and prevent ordinary init/new calls.

The initializer rejects nil, an empty or overlong title, and minutes outside 0 through 120. The title limit uses UTF-16 units and the setter-free public API preserves this toy record after initialization. init/new are unavailable at compile time; this is an API contract, not protection against runtime reflection or hostile subclassing.

Expected stdout:

Read: 20
Empty title: rejected

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
NS_ASSUME_NONNULL_BEGIN
@interface AtlasRecord : NSObject
@property (nonatomic, copy, readonly) NSString *title;
@property (nonatomic, readonly) NSInteger minutes;
- (nullable instancetype)initWithTitle:(nullable NSString *)title minutes:(NSInteger)minutes;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
@end
@implementation AtlasRecord
- (nullable instancetype)initWithTitle:(nullable NSString *)title minutes:(NSInteger)minutes {
    if (title == nil || title.length == 0 || title.length > 40 || minutes < 0 || minutes > 120) {
        return nil;
    }
    self = [super init];
    if (self) { _title = [title copy]; _minutes = minutes; }
    return self;
}
@end
NS_ASSUME_NONNULL_END
int main(void) {
    @autoreleasepool {
        NSMutableString *title = [NSMutableString stringWithString:@"Read"];
        AtlasRecord *record = [[AtlasRecord alloc] initWithTitle:title minutes:20];
        if (record == nil) { return 2; }
        [title appendString:@" more"];
        printf("%s: %ld\n", [record.title UTF8String], (long)record.minutes);
        AtlasRecord *invalid = [[AtlasRecord alloc] initWithTitle:@"" minutes:20];
        puts(invalid == nil ? "Empty title: rejected" : "Unexpected acceptance");
    }
    return 0;
}
Objective-C exercise B - A stable report

Try it first: Format the trusted coding/reading totals in sorted key order, one line per key. Return an empty string for an empty dictionary.

This function accepts trusted dictionaries of short ASCII string keys and small integer NSNumber values. It does not validate a dynamic JSON boundary or arbitrary numeric ranges. Sorting keys produces stable output; an empty dictionary produces an empty string.

Expected stdout:

code: 40
read: 20
Empty report length: 0

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
static NSString *AtlasReport(NSDictionary<NSString *, NSNumber *> *totals) {
    NSMutableArray<NSString *> *lines = [NSMutableArray array];
    for (NSString *key in [[totals allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
        [lines addObject:[NSString stringWithFormat:@"%@: %ld", key, (long)[totals[key] integerValue]]];
    }
    return [lines componentsJoinedByString:@"\n"];
}
int main(void) {
    @autoreleasepool {
        NSDictionary<NSString *, NSNumber *> *totals = @{@"read": @20, @"code": @40};
        puts([AtlasReport(totals) UTF8String]);
        printf("Empty report length: %lu\n", (unsigned long)AtlasReport(@{}).length);
    }
    return 0;
}
Objective-C exercise C - An explicit error contract

Try it first: Implement a small ASCII-only minutes parser with a nullable NSNumber result and optional NSError output. Accept leading zeros but reject signs, whitespace, non-ASCII digits, empty input and values above 120.

The parser accepts one to three ASCII digits with value 0 through 120, including leading zeros. The length bound keeps intermediate arithmetic small. A successful return does not promise to clear an existing NSError output. Eight comparisons execute in main; their unexpected-mismatch branch is not deliberately executed.

Expected stdout:

Cases: 8 passed

Test record: passed; Apple clang version 21.0.0 (clang-2100.3.34.2); ARC; C17 base; macOS SDK 27.0 headers; system Foundation 6.9 (5027.0.69); 2026-10-26. macOS-27.0.1-arm64-arm-64bit

#import <Foundation/Foundation.h>
#include <stdio.h>
NS_ASSUME_NONNULL_BEGIN
static NSNumber * _Nullable AtlasParseMinutes(NSString * _Nullable text,
    NSError * _Nullable __autoreleasing * _Nullable error) {
    if (text != nil && text.length >= 1 && text.length <= 3) {
        NSInteger value = 0;
        BOOL valid = YES;
        for (NSUInteger i = 0; i < text.length; i += 1) {
            unichar unit = [text characterAtIndex:i];
            if (unit < '0' || unit > '9') { valid = NO; break; }
            value = value * 10 + (unit - '0');
        }
        if (valid && value <= 120) { return @(value); }
    }
    if (error != NULL) { *error = [NSError errorWithDomain:@"AtlasMinutes" code:1 userInfo:nil]; }
    return nil;
}
NS_ASSUME_NONNULL_END
int main(void) {
    @autoreleasepool {
        NSArray<NSString *> *inputs = @[@"0", @"20", @"120", @"121", @"+2", @"", @" 2", @"002"];
        NSArray *expected = @[@0, @20, @120, [NSNull null], [NSNull null], [NSNull null], [NSNull null], @2];
        NSUInteger passed = 0;
        for (NSUInteger i = 0; i < inputs.count; i += 1) {
            NSError *error = nil;
            NSNumber *actual = AtlasParseMinutes(inputs[i], &error);
            BOOL accepted = expected[i] != [NSNull null];
            BOOL correct = accepted ? [actual isEqual:expected[i]] : (actual == nil && error != nil);
            if (!correct) { fputs("Unexpected test result\n", stderr); return 2; }
            passed += 1;
        }
        printf("Cases: %lu passed\n", (unsigned long)passed);
    }
    return 0;
}

Expected compiler and warning-policy rejections

Four authored fixtures were rejected under the recorded Apple Clang and ARC configuration. Two are warnings promoted to errors by -Werror; independent syntax-only controls accepted those two without -Werror. No rejection fixture was executed. These results are separate from the twelve accepted runtime programs. Diagnostic wording is implementation-specific.

Expected rejection: Objective-C 01 - Objects and messages

Expected rejection under this pack's compiler configuration; fixture not executed. Observed diagnostic category on the stated compiler: no visible @interface.

Classification: unknown method rejected by this compiler and ARC configuration

#import <Foundation/Foundation.h>
int main(void) { @autoreleasepool { (void)[@"x" atlasMissingMethod]; } }
Expected rejection: Objective-C 05 - A protocol and a category

Expected rejection under this pack's compiler configuration; fixture not executed. Observed diagnostic category on the stated compiler: -Wprotocol.

Classification: missing required protocol implementation: warning promoted by -Werror

#import <Foundation/Foundation.h>
@protocol Required <NSObject>
- (NSString *)summary;
@end
@interface Missing : NSObject <Required>
@end
@implementation Missing
@end
Expected rejection: Objective-C 06 - Weak ownership and a block

Expected rejection under this pack's compiler configuration; fixture not executed. Observed diagnostic category on the stated compiler: forbids explicit message send.

Classification: explicit release forbidden with ARC enabled

#import <Foundation/Foundation.h>
int main(void) { @autoreleasepool { NSObject *value = [NSObject new]; [value release]; } }
Expected rejection: Objective-C exercise C - An explicit error contract

Expected rejection under this pack's compiler configuration; fixture not executed. Observed diagnostic category on the stated compiler: -Wobjc-literal-conversion.

Classification: lightweight generic mismatch: warning promoted by -Werror

#import <Foundation/Foundation.h>
int main(void) { @autoreleasepool { NSArray<NSString *> *names = @[@1]; (void)names; } }

Prompt workbench

Build, edit and export a prompt. It stays on this device until you choose to copy it elsewhere. No AI service is called.

Portable presets

Save up to 20 presets. Import accepts only this version's bounded JSON schema (64 KiB maximum), replaces the session collection and never runs code. Export before importing if you want to preserve the current set.

Optional browser storage

Nothing is stored automatically. localStorage for local files varies by browser, may be blocked or cleared, and is not encrypted. Do not store secrets. Export JSON for a durable copy.

Coverage and next steps

All current editions are generated from one versioned JSON model. The shared renderer creates each individual pack and the combined edition from the same pack records. Planned records carry empty source lists and null verification dates rather than invented evidence. 'Tested' applies to a pack's recorded examples, not an entire language. Frameworks and runtimes are overlays. A dialect is counted as a named scope, not as a claim of an independent language.

  1. planned: Named scope only; source and runtime research pending.
  2. sourced: Relevant official sources verified.
  3. drafted: Original pack authored; checks pending.
  4. tested: Documented examples passed the recorded tests.
  5. reviewed: Functional, accessibility and content review completed for defined scope.
  6. released: Versioned downloadable edition published to the agreed local or Library destination.

Further packs follow actual need. All current packs retain introductory scope; 257 registry entries remain planned. Before each pack: verify official sources, choose versions and operating systems, author original examples, test expected outputs and review accessibility and risk.

Intended future homes

Local and downloadable. Website publication is outside this authoring release. Library save identities and versions are recorded in separate delivery receipts.

Limits: one browser and operating system were tested. An independent agent audited the content. No screen-reader session, formal accessibility certification or outside human review is claimed. Planned entries still need official-source research. No Treasure workbench artifact was present in this isolated workspace; no private corpus was used.

Official sources checked

Original explanations and examples; no documentation mirror. URLs are plain text so this offline edition does not open remote pages by itself.

GNU web manual retrieval timed out and the Open Group full shell specification returned HTTP 403. Shell explanations were verified against installed official manuals, accessible Zsh documentation and actual runtime behavior. POSIX-style denotes the deliberately conservative syntax subset, not certification or a complete standards audit. Zsh web documentation describes 5.9.2; execution used installed 5.9. TypeScript 6.0.3 was located in an existing installed package and is invoked directly; no package manager is used. Its static checks and Node 24.18.0 runtime evidence are separate. Data examples use unsupported CPython 3.9.6. Python 3.9 online documentation describes 3.9.25. TOML uses installed pip-vendored Tomli 1.0.3, a private environment-specific API. The upstream tagged Tomli source page could not be retrieved; version is local metadata, behavior is actual execution, and syntax claims use the TOML 1.0 specification. Python 3.11 tomllib documentation is a compatibility reference only; that branch was not executed. No TOML 1.1, JSON Schema, XSD, hostile XML safety or general standards-conformance claim is made. C17 N2176 and C++20 N4861 PDF retrieval failed; the C11 N1570 committee draft was accessible for core semantics unchanged in this exercised C17 subset. C++ living draft and Core Guidelines references support only the stated concepts; later APIs shown by current draft pages are excluded. Actual Apple Clang 21.0.0 C17/C++20 probes passed and reported libc++ 220106. Upstream status pages do not guarantee Apple compiler completeness. Sanitizer and runtime evidence applies only to these executed paths. Ruby API references are version 2.6.0 documentation for the 2.6 series; actual execution is 2.6.10p210, which is end of life. Perl references are pinned to 5.34.1, the actual installed interpreter. Core module versions are recorded in runtime evidence; no packages were downloaded. No Ruby 3 or newer Perl compatibility is claimed. The Ruby tmpdir HTML URL and Perl perlrun HTML page could not be retrieved; their official repository files at Ruby v2_6_10 and Perl v5.34.1 were read instead. Swift web pages required JavaScript; the official Swift book repository source was accessible. Current book content is limited here to exercised Swift 6 core features. GNU website manual requests timed out; the upstream 3.81 manual source mirror and installed make(1) were used. Swift compile/run and Make dependency tests apply only to this installed macOS arm64 environment; no new toolchain was installed. For awk and sed, POSIX Issue 8 web requests returned HTTP 403. Installed awk(1), sed(1) and re_format(7), plus accessible maintainer documentation, support the exercised subset. awk reports 20200816; the current upstream manual includes later --csv support that is explicitly excluded. sed is identified by macOS 27.0.1 and binary SHA-256, not an invented version. All new stream tests use LC_ALL=C and authored ASCII input; no GNU-tool or Unicode-grapheme compatibility is claimed. jq is the Apple jq-1.7.1-apple build, verified against the upstream 1.7 manual and installed jq(1). xsltproc reports libxslt 1.1.35 and libxml2 2.9.13. The accessible XSLT and XPath 1.0 specifications support only this introductory subset; later language versions are excluded. Current libxslt command documentation is checked against actual installed invocation. No DTD declaration, custom/external entity, document(), import/include, extension or untrusted source is exercised. The independent XPath registry entry stays planned. Predefined XML escapes and numeric character references are used. Installed --stringparam rejects values containing both quote styles. Tcl uses installed 8.5.9; accessible official web references are 8.5.19 series documentation, with differences bounded by actual examples. The proc web page timed out, so its installed manual was read. Expect 5.45 embeds Tcl 8.5.9; the installed official manual supports its options and process semantics. The historical Expect project points to a newer successor; no successor or modern Tcl feature is claimed. Only authored workspace fixtures are spawned; no network, sign-ins, secrets or live application control. Objective-C is pinned to Apple Clang 21.0.0 with ARC, C17 base syntax, macOS SDK 27.0 headers, system Foundation 6.9 (5027.0.69) and macOS 27.0.1 arm64. Apple language and string guides are archived; dated UI/network recipes and broad platform recommendations are excluded. Upstream Clang documents are checked against the locally exercised subset. Current JSONSerialization web content required JavaScript and its linked Markdown request failed; installed SDK NSJSONSerialization.h and NSData.h declarations/comments plus execution support the narrow parsing, error and no-overwrite claims. No JSON-schema, iOS, GNUstep, cross-platform, Objective-C++ or complete memory-safety claim is made.

  1. MDN: Basic HTML syntax
    https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Structuring_content/Basic_HTML_syntax
    Checked 2026-10-25. Scope: Elements, attributes, nesting and document structure.
  2. WHATWG HTML Living Standard
    https://html.spec.whatwg.org/multipage/
    Checked 2026-10-25. Scope: HTML semantics and document structure; living standard.
  3. MDN: Getting started with CSS
    https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Styling_basics/Getting_started
    Checked 2026-10-25. Scope: Selectors, declarations and classes.
  4. MDN: Introduction to the CSS box model
    https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Box_model/Introduction
    Checked 2026-10-25. Scope: Content, padding, border and margin.
  5. W3C: CSS Display Module Level 3
    https://www.w3.org/TR/css-display-3/
    Checked 2026-10-25. Scope: Block and inline layout; candidate recommendation draft, not a browser support promise.
  6. MDN: JavaScript functions
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
    Checked 2026-10-25. Scope: Parameters, return values and function scope.
  7. MDN: Node.textContent
    https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
    Checked 2026-10-25. Scope: Plain text DOM updates rather than markup insertion.
  8. MDN: addEventListener
    https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
    Checked 2026-10-25. Scope: Registering event handlers.
  9. MDN: label element
    https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/label
    Checked 2026-10-25. Scope: Explicit form label association.
  10. MDN: Window.localStorage
    https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
    Checked 2026-10-25. Scope: file: persistence is not guaranteed and access can throw.
  11. W3C: WCAG 2.2
    https://www.w3.org/TR/WCAG22/
    Checked 2026-10-25. Scope: Keyboard operation, labels, visible focus and text contrast. No conformance certification claimed.
  12. MDN: Basic concepts of grid layout
    https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Grid_layout/Basic_concepts
    Checked 2026-10-25. Scope: Grid tracks, repeat(3, 1fr) and gap.
  13. MDN: Using media queries
    https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Media_queries/Using
    Checked 2026-10-25. Scope: Inclusive min-width viewport queries.
  14. MDN: Array.prototype.filter
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
    Checked 2026-10-25. Scope: Selecting a matching subset without changing the source array.
  15. MDN: Array.prototype.reduce
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
    Checked 2026-10-25. Scope: Accumulation and an explicit initial value.
  16. MDN: Number.isFinite
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite
    Checked 2026-10-25. Scope: Finite-number checks without coercion.
  17. Python 3.9 tutorial: Introduction
    https://docs.python.org/3.9/tutorial/introduction.html
    Checked 2026-10-25. Scope: Numbers, strings, lists and basic output.
  18. Python 3.9 tutorial: Control flow
    https://docs.python.org/3.9/tutorial/controlflow.html
    Checked 2026-10-25. Scope: if, for, range, function definitions and return values.
  19. Python 3.9 tutorial: Data structures
    https://docs.python.org/3.9/tutorial/datastructures.html
    Checked 2026-10-25. Scope: Lists, tuples, dictionaries, sets and comprehensions.
  20. Python 3.9 tutorial: Input and output
    https://docs.python.org/3.9/tutorial/inputoutput.html
    Checked 2026-10-25. Scope: Explicit text encoding, context managers and formatted output.
  21. Python 3.9 tutorial: Errors and exceptions
    https://docs.python.org/3.9/tutorial/errors.html
    Checked 2026-10-25. Scope: Specific exception handling and cleanup.
  22. Python 3.9 tutorial: Modules
    https://docs.python.org/3.9/tutorial/modules.html
    Checked 2026-10-25. Scope: Module imports and the __name__ main guard.
  23. Python 3.9 library: unittest
    https://docs.python.org/3.9/library/unittest.html
    Checked 2026-10-25. Scope: TestCase assertions and test runners.
  24. Python 3.9 library: tempfile
    https://docs.python.org/3.9/library/tempfile.html
    Checked 2026-10-25. Scope: TemporaryDirectory lifecycle and cleanup.
  25. Python 3.9 library: pathlib
    https://docs.python.org/3.9/library/pathlib.html
    Checked 2026-10-25. Scope: Path composition and UTF-8 text file operations.
  26. Python 3.9 library: json
    https://docs.python.org/3.9/library/json.html
    Checked 2026-10-25. Scope: JSON encoding/decoding and bounded input cautions.
  27. Python Developer Guide: version status
    https://devguide.python.org/versions/
    Checked 2026-10-25. Scope: Python 3.9 is no longer supported; the installed 3.9.6 runtime is a recorded local teaching environment, not a deployment recommendation.
  28. Python 3.9 library: Built-in types
    https://docs.python.org/3.9/library/stdtypes.html
    Checked 2026-10-25. Scope: Boolean and integer relationship, dictionary insertion order and string casefold.
  29. SQLite SELECT
    https://www.sqlite.org/lang_select.html
    Checked 2026-10-25. Scope: Filtering, ordering and explicit joins.
  30. SQLite CREATE TABLE
    https://www.sqlite.org/lang_createtable.html
    Checked 2026-10-25. Scope: Keys, NOT NULL and CHECK constraints.
  31. SQLite transactions
    https://www.sqlite.org/lang_transaction.html
    Checked 2026-10-25. Scope: BEGIN, COMMIT, ROLLBACK and single-writer scope.
  32. SQLite expressions
    https://www.sqlite.org/lang_expr.html
    Checked 2026-10-25. Scope: NULL, CASE, comparisons and named parameters.
  33. SQLite command-line shell
    https://www.sqlite.org/cli.html
    Checked 2026-10-25. Scope: In-memory execution, safe mode, dot commands and the expression-evaluating .parameter command.
  34. SQLite foreign keys
    https://www.sqlite.org/foreignkeys.html
    Checked 2026-10-25. Scope: Enable enforcement per connection before a transaction.
  35. SQLite datatypes
    https://www.sqlite.org/datatype3.html
    Checked 2026-10-25. Scope: Dynamic typing and affinity; no cross-dialect type guarantee.
  36. SQLite quirks
    https://www.sqlite.org/quirks.html
    Checked 2026-10-25. Scope: Differences from other SQL implementations.
  37. SQLite aggregate functions
    https://www.sqlite.org/lang_aggfunc.html
    Checked 2026-10-25. Scope: COUNT, SUM and empty or NULL input.
  38. SQLite WITH clause
    https://www.sqlite.org/lang_with.html
    Checked 2026-10-25. Scope: Ordinary statement-scoped common table expressions.
  39. SQLite value binding API
    https://www.sqlite.org/c3ref/bind_blob.html
    Checked 2026-10-25. Scope: Bind literal values separately from statement structure; API discussion only, not an executed C example.
  40. Installed Bash 3.2 manual
    man:bash(1)
    Checked 2026-10-25. Scope: Quoting, positional parameters, loops, functions, arrays, redirections and pipeline status. Read from /usr/share/man/man1/bash.1.
  41. Installed macOS sh manual
    man:sh(1)
    Checked 2026-10-25. Scope: macOS sh selects an implementation; this host selects /bin/bash 3.2.57.
  42. Installed macOS mktemp manual
    man:mktemp(1)
    Checked 2026-10-25. Scope: Create a unique directory using a template; platform utility, not a portable POSIX utility claim.
  43. Zsh shell grammar
    https://zsh.sourceforge.io/Doc/Release/Shell-Grammar.html
    Checked 2026-10-25. Scope: Pipelines, conditionals, quoting and exit status.
  44. Zsh parameters
    https://zsh.sourceforge.io/Doc/Release/Parameters.html
    Checked 2026-10-25. Scope: Native array indexing and parameter behavior.
  45. Zsh options
    https://zsh.sourceforge.io/Doc/Release/Options.html
    Checked 2026-10-25. Scope: Native options, SH_WORD_SPLIT and pipeline behavior.
  46. TypeScript: The basics
    https://www.typescriptlang.org/docs/handbook/2/basic-types.html
    Checked 2026-10-25. Scope: Static checks, erased types and JavaScript output.
  47. TypeScript: Everyday types
    https://www.typescriptlang.org/docs/handbook/2/everyday-types.html
    Checked 2026-10-25. Scope: Primitive, union and object types.
  48. TypeScript: Narrowing
    https://www.typescriptlang.org/docs/handbook/2/narrowing.html
    Checked 2026-10-25. Scope: Guards, discriminators and never.
  49. TypeScript: Functions
    https://www.typescriptlang.org/docs/handbook/2/functions.html
    Checked 2026-10-25. Scope: Function signatures and unknown.
  50. TypeScript: Object types
    https://www.typescriptlang.org/docs/handbook/2/objects.html
    Checked 2026-10-25. Scope: Optional and readonly fields.
  51. TypeScript: Generics
    https://www.typescriptlang.org/docs/handbook/2/generics.html
    Checked 2026-10-25. Scope: Relationships between types.
  52. TypeScript: strict
    https://www.typescriptlang.org/tsconfig/strict.html
    Checked 2026-10-25. Scope: Strict checking group.
  53. TypeScript: noEmitOnError
    https://www.typescriptlang.org/tsconfig/noEmitOnError.html
    Checked 2026-10-25. Scope: Suppress output on errors.
  54. TypeScript: noUncheckedIndexedAccess
    https://www.typescriptlang.org/tsconfig/noUncheckedIndexedAccess.html
    Checked 2026-10-25. Scope: Unchecked indices include undefined.
  55. TypeScript: exactOptionalPropertyTypes
    https://www.typescriptlang.org/tsconfig/exactOptionalPropertyTypes.html
    Checked 2026-10-25. Scope: Absent versus undefined fields.
  56. TypeScript: Module reference
    https://www.typescriptlang.org/docs/handbook/modules/reference.html
    Checked 2026-10-25. Scope: Node16 and extension resolution.
  57. IETF RFC 8259: JSON
    https://www.rfc-editor.org/rfc/rfc8259
    Checked 2026-10-25. Scope: JSON syntax and interoperability.
  58. Python 3.9: json
    https://docs.python.org/3.9/library/json.html
    Checked 2026-10-25. Scope: Parser defaults, hooks and serializer.
  59. IETF RFC 4180: CSV
    https://www.rfc-editor.org/rfc/rfc4180
    Checked 2026-10-25. Scope: Common CSV form; informational RFC, not all dialects.
  60. Python 3.9: csv
    https://docs.python.org/3.9/library/csv.html
    Checked 2026-10-25. Scope: Dialects, reader/writer and newline handling.
  61. W3C XML 1.0 fifth edition
    https://www.w3.org/TR/xml/
    Checked 2026-10-25. Scope: Well-formed XML and escaping.
  62. Python 3.9: ElementTree
    https://docs.python.org/3.9/library/xml.etree.elementtree.html
    Checked 2026-10-25. Scope: Tree construction, namespaces and parsing.
  63. Python 3.9: XML vulnerabilities
    https://docs.python.org/3.9/library/xml.html#xml-vulnerabilities
    Checked 2026-10-25. Scope: Untrusted XML boundary.
  64. TOML 1.0.0 specification
    https://toml.io/en/v1.0.0
    Checked 2026-10-25. Scope: TOML 1.0 syntax and typed values.
  65. Python 3.11: tomllib
    https://docs.python.org/3.11/library/tomllib.html
    Checked 2026-10-25. Scope: Available since 3.11; documentation only, not installed execution evidence.
  66. WG14 N1570 C11 committee draft
    https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
    Checked 2026-10-25. Scope: Core objects, arrays, functions, storage duration, formatted output, allocation and conversion semantics used in the C17 subset; not a C17 draft or full-conformance claim.
  67. Clang compiler user manual
    https://clang.llvm.org/docs/UsersManual.html
    Checked 2026-10-25. Scope: Compiler driver, standard modes and diagnostics; upstream documentation is not an Apple feature guarantee.
  68. Clang C implementation status
    https://clang.llvm.org/c_status.html
    Checked 2026-10-25. Scope: C mode support and known limits; actual examples pin Apple Clang C17.
  69. Clang C++ implementation status
    https://clang.llvm.org/cxx_status.html
    Checked 2026-10-25. Scope: C++20 mode and partial feature coverage; actual subset tested locally.
  70. libc++ C++20 implementation status
    https://libcxx.llvm.org/Status/Cxx20.html
    Checked 2026-10-25. Scope: Library feature status; Apple-shipped version verified locally.
  71. C++ Core Guidelines
    https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
    Checked 2026-10-25. Scope: Ownership, lifetimes and resource management guidance, not normative standard text.
  72. C++ working draft: object lifetime
    https://eel.is/c++draft/basic.life
    Checked 2026-10-25. Scope: Living working draft; lifetime concepts only, not a C++20 publication.
  73. C++ working draft: unique ownership
    https://eel.is/c++draft/unique.ptr
    Checked 2026-10-25. Scope: Living draft; elementary unique_ptr ownership and move semantics, excluding later additions.
  74. C++ working draft: span
    https://eel.is/c++draft/views.span
    Checked 2026-10-25. Scope: Living draft; borrowing and length concepts; later span APIs excluded from C++20 exercises.
  75. C++ working draft: optional
    https://eel.is/c++draft/optional
    Checked 2026-10-25. Scope: Living draft; engaged value and absence only; later APIs excluded.
  76. Clang AddressSanitizer
    https://clang.llvm.org/docs/AddressSanitizer.html
    Checked 2026-10-25. Scope: Instrumented checking of some memory errors on executed paths; not safety proof.
  77. Clang UndefinedBehaviorSanitizer
    https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
    Checked 2026-10-25. Scope: Checks for selected undefined behavior; coverage is incomplete.
  78. C++ working draft: from_chars
    https://eel.is/c++draft/charconv.from.chars
    Checked 2026-10-25. Scope: Living draft; integer error code, end-pointer and no-throw concepts available in the exercised C++20 subset. Later constexpr additions are not used.
  79. Ruby 2.6.10 release and end of life
    https://www.ruby-lang.org/en/news/2022/04/12/ruby-2-6-10-released/
    Checked 2026-10-25. Scope: Installed 2.6.10 is end of life; offline teaching only.
  80. Ruby 2.6 control expressions
    https://docs.ruby-lang.org/en/2.6.0/syntax/control_expressions_rdoc.html
    Checked 2026-10-25. Scope: Truth values, branches, loops and blocks.
  81. Ruby 2.6 methods
    https://docs.ruby-lang.org/en/2.6.0/syntax/methods_rdoc.html
    Checked 2026-10-25. Scope: Method parameters and return semantics.
  82. Ruby 2.6 Kernel
    https://docs.ruby-lang.org/en/2.6.0/Kernel.html
    Checked 2026-10-25. Scope: Integer conversion, exceptions, require_relative and Kernel.open process boundary.
  83. Ruby 2.6 Array
    https://docs.ruby-lang.org/en/2.6.0/Array.html
    Checked 2026-10-25. Scope: Array iteration and shallow collection copying.
  84. Ruby 2.6 Hash
    https://docs.ruby-lang.org/en/2.6.0/Hash.html
    Checked 2026-10-25. Scope: Keys, fetch and shared defaults.
  85. Ruby 2.6 String
    https://docs.ruby-lang.org/en/2.6.0/String.html
    Checked 2026-10-25. Scope: Mutation, character and byte lengths.
  86. Ruby 2.6 IO
    https://docs.ruby-lang.org/en/2.6.0/IO.html
    Checked 2026-10-25. Scope: Block closing and explicit encoding.
  87. Ruby 2.6.10 tmpdir source documentation
    https://raw.githubusercontent.com/ruby/ruby/v2_6_10/lib/tmpdir.rb
    Checked 2026-10-25. Scope: New temporary directory and block-scoped cleanup.
  88. Ruby 2.6 JSON
    https://docs.ruby-lang.org/en/2.6.0/JSON.html
    Checked 2026-10-25. Scope: Serialization, parsing and object-additions boundary.
  89. Ruby 2.6 modules and classes
    https://docs.ruby-lang.org/en/2.6.0/syntax/modules_and_classes_rdoc.html
    Checked 2026-10-25. Scope: Namespaces and singleton methods.
  90. Perl 5.34.1 introduction
    https://perldoc.perl.org/5.34.1/perlintro
    Checked 2026-10-25. Scope: Scalar/list context, truth, lexical variables and control flow.
  91. Perl 5.34.1 subroutines
    https://perldoc.perl.org/5.34.1/perlsub
    Checked 2026-10-25. Scope: Argument array and explicit returns.
  92. Perl 5.34.1 references
    https://perldoc.perl.org/5.34.1/perlref
    Checked 2026-10-25. Scope: Nested arrays, references and aliasing.
  93. Perl 5.34.1 regular expressions
    https://perldoc.perl.org/5.34.1/perlre
    Checked 2026-10-25. Scope: Whole-string anchors and literal quoting.
  94. Perl 5.34.1 open
    https://perldoc.perl.org/5.34.1/functions/open
    Checked 2026-10-25. Scope: Three-argument open, lexical handles and encoding layers.
  95. Perl 5.34.1 File::Temp
    https://perldoc.perl.org/5.34.1/File::Temp
    Checked 2026-10-25. Scope: Unique toy directory and normal-exit cleanup.
  96. Perl 5.34.1 JSON::PP
    https://perldoc.perl.org/5.34.1/JSON::PP
    Checked 2026-10-25. Scope: Canonical encoding, bounded parser and scalar representation limits.
  97. Perl 5.34.1 modules
    https://perldoc.perl.org/5.34.1/perlmod
    Checked 2026-10-25. Scope: Package namespace and module loading.
  98. Perl 5.34.1 invocation
    https://raw.githubusercontent.com/Perl/perl5/v5.34.1/pod/perlrun.pod
    Checked 2026-10-25. Scope: Syntax checking may run compile-time code; not an arbitrary-code sandbox.
  99. Perl 5.34.1 Test::More
    https://perldoc.perl.org/5.34.1/Test::More
    Checked 2026-10-25. Scope: Named executed tests and TAP plan.
  100. Ruby 2.6 Encoding
    https://docs.ruby-lang.org/en/2.6.0/Encoding.html
    Checked 2026-10-25. Scope: ASCII-compatible encoding guard; valid encoding is separate from application syntax.
  101. Swift book: The Basics
    https://raw.githubusercontent.com/swiftlang/swift-book/main/TSPL.docc/LanguageGuide/TheBasics.md
    Checked 2026-10-25. Scope: Types, constants and optionals.
  102. Swift book: Collection Types
    https://raw.githubusercontent.com/swiftlang/swift-book/main/TSPL.docc/LanguageGuide/CollectionTypes.md
    Checked 2026-10-25. Scope: Array, set and dictionary semantics.
  103. Swift book: Structures and Classes
    https://raw.githubusercontent.com/swiftlang/swift-book/main/TSPL.docc/LanguageGuide/ClassesAndStructures.md
    Checked 2026-10-25. Scope: Value versus reference semantics.
  104. Swift book: Functions
    https://raw.githubusercontent.com/swiftlang/swift-book/main/TSPL.docc/LanguageGuide/Functions.md
    Checked 2026-10-25. Scope: Parameters, labels, return values and bounds-oriented function design.
  105. Swift book: Strings and Characters
    https://raw.githubusercontent.com/swiftlang/swift-book/main/TSPL.docc/LanguageGuide/StringsAndCharacters.md
    Checked 2026-10-25. Scope: Character, Unicode representation and string indexing.
  106. Swift book: Error Handling
    https://raw.githubusercontent.com/swiftlang/swift-book/main/TSPL.docc/LanguageGuide/ErrorHandling.md
    Checked 2026-10-25. Scope: Throws, try and recoverable errors.
  107. GNU Make 3.81 manual source
    https://raw.githubusercontent.com/mirror/make/3.81/doc/make.texi
    Checked 2026-10-25. Scope: Pinned upstream manual: rules, variables, recipes, automatic variables, order-only prerequisites and failure behavior.
  108. Installed GNU Make command manual
    man:make(1)
    Checked 2026-10-25. Scope: Installed command flags; read with man make on this tested Mac.
  109. Swift book: Control Flow
    https://raw.githubusercontent.com/swiftlang/swift-book/main/TSPL.docc/LanguageGuide/ControlFlow.md
    Checked 2026-10-25. Scope: Branches, switch exhaustiveness and loops.
  110. Swift book: Automatic Reference Counting
    https://raw.githubusercontent.com/swiftlang/swift-book/main/TSPL.docc/LanguageGuide/AutomaticReferenceCounting.md
    Checked 2026-10-25. Scope: Class instance lifetime and reference ownership; cycles are outside the exercised examples.
  111. Installed awk manual
    man:awk(1)
    Checked 2026-10-26. Scope: Installed 20200816 rules, records, fields, arrays, functions and I/O boundaries.
  112. One True Awk maintainer manual
    https://raw.githubusercontent.com/onetrueawk/awk/master/awk.1
    Checked 2026-10-26. Scope: Core semantics only; newer --csv support is excluded from this installed version.
  113. Installed macOS sed manual
    man:sed(1)
    Checked 2026-10-26. Scope: Editing cycle, addresses, substitution, hold space, branching and command-line flags.
  114. Apple sed manual source
    https://raw.githubusercontent.com/apple-oss-distributions/text_cmds/main/sed/sed.1
    Checked 2026-10-26. Scope: Apple-maintained documentation; local binary and execution evidence remain authoritative.
  115. Installed regular-expression manual
    man:re_format(7)
    Checked 2026-10-26. Scope: Basic versus extended regular expressions; ASCII C-locale scope.
  116. jq 1.7 manual
    https://jqlang.org/manual/v1.7/
    Checked 2026-10-26. Scope: Filter semantics, data parameters, input/output options and exit statuses.
  117. Installed jq manual
    man:jq(1)
    Checked 2026-10-26. Scope: Installed Apple jq 1.7.1 command-line behavior; executed examples remain authoritative.
  118. W3C XSLT 1.0 Recommendation
    https://www.w3.org/TR/xslt-10/
    Checked 2026-10-26. Scope: Templates, parameters, variables, keys, messages and serialization; version 1.0 only.
  119. W3C XPath 1.0 Recommendation
    https://www.w3.org/TR/1999/REC-xpath-19991116/
    Checked 2026-10-26. Scope: Supporting node selection, predicates, conversion and core functions only; standalone XPath remains planned.
  120. libxslt xsltproc manual
    https://gnome.pages.gitlab.gnome.org/libxslt/xsltproc.html
    Checked 2026-10-26. Scope: Command options, safety limits and separation of stylesheet/application errors.
  121. Installed xsltproc manual
    man:xsltproc(1)
    Checked 2026-10-26. Scope: Installed libxslt 1.1.35 with libxml2 2.9.13; only local authored inputs and trusted stylesheets.
  122. Tcl 8.5 command syntax
    https://www.tcl-lang.org/man/tcl8.5/TclCmd/Tcl.htm
    Checked 2026-10-26. Scope: Command words, substitution and grouping; web manual 8.5.19, tested interpreter 8.5.9.
  123. Tcl 8.5 list
    https://www.tcl-lang.org/man/tcl8.5/TclCmd/list.htm
    Checked 2026-10-26. Scope: Structured list construction, not script interpolation.
  124. Tcl 8.5 expressions
    https://www.tcl-lang.org/man/tcl8.5/TclCmd/expr.htm
    Checked 2026-10-26. Scope: Braced expressions, numeric forms and comparison.
  125. Tcl 8.5 dictionaries
    https://www.tcl-lang.org/man/tcl8.5/TclCmd/dict.htm
    Checked 2026-10-26. Scope: Presence, accumulation and structured key-value data.
  126. Tcl 8.5 completion codes
    https://www.tcl-lang.org/man/tcl8.5/TclCmd/catch.htm
    Checked 2026-10-26. Scope: catch result/options and exceptional completion codes.
  127. Tcl 8.5 open
    https://www.tcl-lang.org/man/tcl8.5/TclCmd/open.htm
    Checked 2026-10-26. Scope: Exclusive file creation and pipeline-path caveat.
  128. Tcl 8.5 channel configuration
    https://www.tcl-lang.org/man/tcl8.5/TclCmd/fconfigure.htm
    Checked 2026-10-26. Scope: Encoding, newline translation and buffering.
  129. Tcl 8.5 namespaces
    https://www.tcl-lang.org/man/tcl8.5/TclCmd/namespace.htm
    Checked 2026-10-26. Scope: Qualified procedures and trusted namespace definitions.
  130. Installed Tcl proc manual
    man:proc(n)
    Checked 2026-10-26. Scope: Procedure arguments and local scope; web proc retrieval timed out.
  131. Tcl 8.5 series release page
    https://www.tcl-lang.org/software/tcltk/8.5.html
    Checked 2026-10-26. Scope: Historical 8.5 series scope; no modern-runtime recommendation.
  132. Installed Expect manual
    man:expect(1)
    Checked 2026-10-26. Scope: spawn, send, exact/regexp matching, startup flags, timeout, exp_continue, EOF, wait and pseudo-terminal configuration.
  133. Expect project and successor notice
    https://core.tcl-lang.org/expect/index
    Checked 2026-10-26. Scope: Tcl extension role and old project notice; modern successor features excluded.
  134. Apple: About Objective-C
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html
    Checked 2026-10-26. Scope: Language and framework distinction. Archived guide; historical UI and network recipes excluded.
  135. Apple: Defining Classes
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html
    Checked 2026-10-26. Scope: Interfaces, implementations and method declarations. Archived guide; historical UI and network recipes excluded.
  136. Apple: Working with Objects
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html
    Checked 2026-10-26. Scope: Messages, initialization and nil. Archived guide; historical UI and network recipes excluded.
  137. Apple: Encapsulating Data
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html
    Checked 2026-10-26. Scope: Property copying, ARC relationships and weak references. Archived guide; historical UI and network recipes excluded.
  138. Apple: Values and Collections
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/FoundationTypesandCollections/FoundationTypesandCollections.html
    Checked 2026-10-26. Scope: Boxing, object collections and absence. Archived guide; historical UI and network recipes excluded.
  139. Apple: Working with Protocols
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html
    Checked 2026-10-26. Scope: Declared protocol contracts. Archived guide; historical UI and network recipes excluded.
  140. Apple: Customizing Existing Classes
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html
    Checked 2026-10-26. Scope: Class extensions and category method naming. Archived guide; historical UI and network recipes excluded.
  141. Apple: Working with Blocks
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html
    Checked 2026-10-26. Scope: Captures, __block and ownership cycles. Archived guide; historical UI and network recipes excluded.
  142. Apple: Dealing with Errors
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ErrorHandling/ErrorHandling.html
    Checked 2026-10-26. Scope: Return values and NSError conventions. Archived guide; historical UI and network recipes excluded.
  143. Clang: Objective-C ARC
    https://clang.llvm.org/docs/AutomaticReferenceCounting.html
    Checked 2026-10-26. Scope: ARC flags and ownership semantics; Apple compiler subset is tested locally.
  144. Clang: Objective-C Literals
    https://clang.llvm.org/docs/ObjectiveCLiterals.html
    Checked 2026-10-26. Scope: Boxing and collection literal semantics; Apple compiler subset is tested locally.
  145. Apple: Characters and Grapheme Clusters
    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/stringsClusters.html
    Checked 2026-10-26. Scope: Archived NSString guide: UTF-16 units, composed sequences and range boundaries.